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 firstname.lastname@example.org. 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find subarray with given sum with negatives allowed in constant space
- Sorting using trivial hash function
- Maximize the difference between two subsets of a set with negatives
- 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
- Convert an array to reduced form | Set 1 (Simple and Hashing)
- Cuckoo Hashing - Worst case O(1) Lookup!
- Top 20 Hashing Technique based Interview Questions
- Hashing | Set 1 (Introduction)
- Hashing | Set 2 (Separate Chaining)
- Union and Intersection of two linked lists | Set-3 (Hashing)
- Practice Problems on Hashing
- C++ program for hashing with chaining
- Double Hashing
- Coalesced hashing
- Majority Element | Set-2 (Hashing)
- Applications of Hashing
- Hashing in Java
- Address Calculation Sort using Hashing
- Find the smallest positive number missing from an unsorted array : Hashing Implementation