Open In App

Implementing own Hash Table with Open Addressing Linear Probing

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite – Hashing Introduction, Implementing our Own Hash Table with Separate Chaining in Java
In Open Addressing, all elements are stored in the hash table itself. So at any point, size of table must be greater than or equal to total number of keys (Note that we can increase table size by copying old data if needed).

  • Insert(k) – Keep probing until an empty slot is found. Once an empty slot is found, insert k.
  • Search(k) – Keep probing until slot’s key doesn’t become equal to k or an empty slot is reached.
  • Delete(k) – Delete operation is interesting. If we simply delete a key, then search may fail. So slots of deleted keys are marked specially as “deleted”.

Here, to mark a node deleted we have used dummy node with key and value -1. 
Insert can insert an item in a deleted slot, but search doesn’t stop at a deleted slot.
The entire process ensures that for any key, we get an integer position within the size of the Hash Table to insert the corresponding value. 
So the process is simple, user gives a (key, value) pair set as input and based on the value generated by hash function an index is generated to where the value corresponding to the particular key is stored. So whenever we need to fetch a value corresponding to a key that is just O(1).
 

Implementation:

CPP





Java





Python3





C#





Javascript





Output

key = 1  value = 1
key = 2  value = 3
2
3
1
0
0

Complexity analysis for Insertion:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N). This happens when all elements have collided and we need to insert the last element by checking free space one by one.
    • Average Case: O(1) for good hash function, O(N) for bad hash function
  • Auxiliary Space: O(1)

Complexity analysis for Deletion:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N)
    • Average Case: O(1) for good hash function; O(N) for bad hash function
  • Auxiliary Space: O(1) 

Complexity analysis for Searching:

  • Time Complexity:
    • Best Case: O(1)
    • Worst Case: O(N)
    • Average Case: O(1) for good hash function; O(N) for bad hash function
  • Auxiliary Space: O(1) for search operation


Last Updated : 25 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads