Given a limited range array contains both positive and non-positive numbers, i.e., elements are in the range from -MAX to +MAX. Our task is to search if some number is present in the array or not in O(1) time.
Since range is limited, we can use index mapping (or trivial hashing). We use values as the index in a big array. Therefore we can search and insert elements in O(1) time.
How to handle negative numbers?
The idea is to use a 2D array of size hash[MAX+1]
Assign all the values of the hash matrix as 0. Traverse the given array: If the element ele is non negative assign hash[ele] as 1. Else take the absolute value of ele and assign hash[ele] as 1.
To search any element x in the array.
- If X is non-negative check if hash[X] is 1 or not. If hash[X] is one then the number is present else not present.
- If X is negative take absolute value of X and then check if hash[X] is 1 or not. If hash[X] is one then the number is present
Below is the implementation of the above idea.
This article is contributed by ShivamKD. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find subarray with given sum with negatives allowed in constant space
- Find a Fixed Point (Value equal to index) in a given array | Duplicates Allowed
- Minimum cost to reach end of array array when a maximum jump of K index is allowed
- Sorting using trivial hash function
- Maximize the difference between two subsets of a set with negatives
- Queries for number of distinct elements from a given index till last index in an array
- Number of permutations such that sum of elements at odd index and even index are equal
- Check if every index i has an index j such that sum of elements in both directions are equal
- Difference between Inverted Index and Forward Index
- Applications of Hashing
- Hashing in Java
- Coalesced hashing
- Double Hashing
- Hashing | Set 1 (Introduction)
- Majority Element | Set-2 (Hashing)