Open In App

Implementing own Hash Table with Open Addressing Linear Probing

Last Updated : 21 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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
#include<bits/stdc++.h>usingnamespacestd;// template for generic typetemplate<typenameK,typenameV>// Hashnode classclassHashNode{public:Vvalue;Kkey;// Constructor of hashnodeHashNode(Kkey,Vvalue){this->value=value;this->key=key;}};// template for generic typetemplate<typenameK,typenameV>// Our own Hashmap classclassHashMap{// hash element arrayHashNode<K,V>**arr;intcapacity;// current sizeintsize;// dummy nodeHashNode<K,V>*dummy;public:HashMap(){// Initial capacity of hash arraycapacity=20;size=0;arr=newHashNode<K,V>*[capacity];// Initialise all elements of array as NULLfor(inti=0;i<capacity;i++)arr[i]=NULL;// dummy node with value and key -1dummy=newHashNode<K,V>(-1,-1);}// This implements hash function to find index// for a keyinthashCode(Kkey){returnkey%capacity;}// Function to add key value pairvoidinsertNode(Kkey,Vvalue){HashNode<K,V>*temp=newHashNode<K,V>(key,value);// Apply hash function to find index for given keyinthashIndex=hashCode(key);// find next free spacewhile(arr[hashIndex]!=NULL&&arr[hashIndex]->key!=key&&arr[hashIndex]->key!=-1){hashIndex++;hashIndex%=capacity;}// if new node to be inserted// increase the current sizeif(arr[hashIndex]==NULL||arr[hashIndex]->key==-1)size++;arr[hashIndex]=temp;}// Function to delete a key value pairVdeleteNode(intkey){// Apply hash function// to find index for given keyinthashIndex=hashCode(key);// finding the node with given keywhile(arr[hashIndex]!=NULL){// if node foundif(arr[hashIndex]->key==key){HashNode<K,V>*temp=arr[hashIndex];// Insert dummy node here for further usearr[hashIndex]=dummy;// Reduce sizesize--;returntemp->value;}hashIndex++;hashIndex%=capacity;}// If not found return nullreturnNULL;}// Function to search the value for a given keyVget(intkey){// Apply hash function to find index for given keyinthashIndex=hashCode(key);intcounter=0;// finding the node with given keywhile(arr[hashIndex]!=NULL){// int counter =0; // BUG!if(counter++>capacity)// to avoid infinite loopreturnNULL;// if node found return its valueif(arr[hashIndex]->key==key)returnarr[hashIndex]->value;hashIndex++;hashIndex%=capacity;}// If not found return nullreturnNULL;}// Return current sizeintsizeofMap(){returnsize;}// Return true if size is 0boolisEmpty(){returnsize==0;}// Function to display the stored key value pairsvoiddisplay(){for(inti=0;i<capacity;i++){if(arr[i]!=NULL&&arr[i]->key!=-1)cout<<"key = "<<arr[i]->key<<" value = "<<arr[i]->value<<endl;}}};// Driver method to test map classintmain(){HashMap<int,int>*h=newHashMap<int,int>;h->insertNode(1,1);h->insertNode(2,2);h->insertNode(2,3);h->display();cout<<h->sizeofMap()<<endl;cout<<h->deleteNode(2)<<endl;cout<<h->sizeofMap()<<endl;cout<<h->isEmpty()<<endl;cout<<h->get(2);return0;}
Java
// Our own HashNode classclassHashNode{intkey;intvalue;publicHashNode(intkey,intvalue){this.key=key;this.value=value;}}// Our own Hashmap classclassHashMap{// hash element arrayintcapacity;intsize;HashNode[]arr;// dummy nodeHashNodedummy;publicHashMap(){this.capacity=20;this.size=0;this.arr=newHashNode[this.capacity];// initialize with dummy nodethis.dummy=newHashNode(-1,-1);}// This implements hash function to find index for a keypublicinthashCode(intkey){returnkey%this.capacity;}// Function to add key value pairpublicvoidinsertNode(intkey,intvalue){HashNodetemp=newHashNode(key,value);// Apply hash function to find index for given keyinthashIndex=hashCode(key);// find next free spacewhile(this.arr[hashIndex]!=null&&this.arr[hashIndex].key!=key&&this.arr[hashIndex].key!=-1){hashIndex++;hashIndex%=this.capacity;}// if new node to be inserted, increase the current// sizeif(this.arr[hashIndex]==null||this.arr[hashIndex].key==-1){this.size++;}this.arr[hashIndex]=temp;}// Function to delete a key value pairpublicintdeleteNode(intkey){// Apply hash function to find index for given keyinthashIndex=hashCode(key);// finding the node with given keywhile(this.arr[hashIndex]!=null){// if node foundif(this.arr[hashIndex].key==key){HashNodetemp=this.arr[hashIndex];// Insert dummy node here for further usethis.arr[hashIndex]=this.dummy;// Reduce sizethis.size--;returntemp.value;}hashIndex++;hashIndex%=this.capacity;}// If not found return -1return-1;}// Function to search the value for a given keypublicintget(intkey){// Apply hash function to find index for given keyinthashIndex=hashCode(key);intcounter=0;// finding the node with given keywhile(this.arr[hashIndex]!=null){// If counter is greater than capacity to avoid// infinite loopif(counter>this.capacity){return-1;}// if node found return its valueif(this.arr[hashIndex].key==key){returnthis.arr[hashIndex].value;}hashIndex++;hashIndex%=this.capacity;counter++;}// If not found return 0return0;}// Return current sizepublicintsizeofMap(){returnthis.size;}// Return true if size is 0publicbooleanisEmpty(){returnthis.size==0;}// Function to display the stored key value pairspublicvoiddisplay(){for(inti=0;i<this.capacity;i++){if(this.arr[i]!=null&&this.arr[i].key!=-1){System.out.println("key = "+this.arr[i].key+" value = "+this.arr[i].value);}}}}publicclassMain{publicstaticvoidmain(String[]args){HashMaph=newHashMap();h.insertNode(1,1);h.insertNode(2,2);h.insertNode(2,3);h.display();System.out.println(h.sizeofMap());System.out.println(h.deleteNode(2));System.out.println(h.sizeofMap());System.out.println(h.isEmpty());System.out.println(h.get(2));}}
Python
# Our own Hashnode classclassHashNode:def__init__(self,key,value):self.key=keyself.value=value# Our own Hashmap classclassHashMap:# hash element arraydef__init__(self):self.capacity=20self.size=0self.arr=[None]*self.capacity# dummy nodeself.dummy=HashNode(-1,-1)# This implements hash function to find index for a keydefhashCode(self,key):returnkey%self.capacity# Function to add key value pairdefinsertNode(self,key,value):temp=HashNode(key,value)# Apply hash function to find index for given keyhashIndex=self.hashCode(key)# find next free spacewhileself.arr[hashIndex]isnotNoneandself.arr[hashIndex].key!=keyandself.arr[hashIndex].key!=-1:hashIndex+=1hashIndex%=self.capacity# if new node to be inserted, increase the current sizeifself.arr[hashIndex]isNoneorself.arr[hashIndex].key==-1:self.size+=1self.arr[hashIndex]=temp# Function to delete a key value pairdefdeleteNode(self,key):# Apply hash function to find index for given keyhashIndex=self.hashCode(key)# finding the node with given keywhileself.arr[hashIndex]isnotNone:# if node foundifself.arr[hashIndex].key==key:temp=self.arr[hashIndex]# Insert dummy node here for further useself.arr[hashIndex]=self.dummy# Reduce sizeself.size-=1returntemp.valuehashIndex+=1hashIndex%=self.capacity# If not found return NonereturnNone# Function to search the value for a given keydefget(self,key):# Apply hash function to find index for given keyhashIndex=self.hashCode(key)counter=0# finding the node with given keywhileself.arr[hashIndex]isnotNone:# If counter is greater than capacity to avoid infinite loopifcounter>self.capacity:returnNone# if node found return its valueifself.arr[hashIndex].key==key:returnself.arr[hashIndex].valuehashIndex+=1hashIndex%=self.capacitycounter+=1# If not found return Nonereturn0# Return current sizedefsizeofMap(self):returnself.size# Return true if size is 0defisEmpty(self):returnself.size==0# Function to display the stored key value pairsdefdisplay(self):foriinrange(self.capacity):ifself.arr[i]isnotNoneandself.arr[i].key!=-1:print("key = ",self.arr[i].key," value = ",self.arr[i].value)# Driver method to test map classif__name__=="__main__":h=HashMap()h.insertNode(1,1)h.insertNode(2,2)h.insertNode(2,3)h.display()print(h.sizeofMap())print(h.deleteNode(2))print(h.sizeofMap())print(h.isEmpty())print(h.get(2))
C#
usingSystem;classHashNode{publicintkey;publicintvalue;publicHashNodenext;publicHashNode(intkey,intvalue){this.key=key;this.value=value;next=null;}}classHashMap{privateHashNode[]table;privateintcapacity;privateintsize;publicHashMap(intcapacity){this.capacity=capacity;table=newHashNode[capacity];size=0;}// hash function to find index for a given keyprivateintHashCode(intkey){returnkey%capacity;}// function to add key value pairpublicvoidInsertNode(intkey,intvalue){inthashIndex=HashCode(key);HashNodenewNode=newHashNode(key,value);// if the key already exists, update the valueif(table[hashIndex]!=null){HashNodecurrent=table[hashIndex];while(current!=null){if(current.key==key){current.value=value;return;}current=current.next;}}// if the key is new, add a new node to the tablenewNode.next=table[hashIndex];table[hashIndex]=newNode;size++;}// function to delete a key value pairpublicint?DeleteNode(intkey){inthashIndex=HashCode(key);if(table[hashIndex]!=null){HashNodecurrent=table[hashIndex];HashNodeprevious=null;while(current!=null){if(current.key==key){if(previous==null){table[hashIndex]=current.next;}else{previous.next=current.next;}size--;returncurrent.value;}previous=current;current=current.next;}}returnnull;}// function to get the value for a given keypublicint?Get(intkey){inthashIndex=HashCode(key);if(table[hashIndex]!=null){HashNodecurrent=table[hashIndex];while(current!=null){if(current.key==key){returncurrent.value;}current=current.next;}}return0;}// function to get the number of key value pairs in the// hashmappublicintSize(){returnsize;}// function to check if the hashmap is emptypublicboolIsEmpty(){returnsize==0;}// function to display the key value pairs in the// hashmappublicvoidDisplay(){for(inti=0;i<capacity;i++){if(table[i]!=null){HashNodecurrent=table[i];while(current!=null){Console.WriteLine("key = "+current.key+" value = "+current.value);current=current.next;}}}}}classProgram{staticvoidMain(string[]args){HashMaph=newHashMap(20);h.InsertNode(1,1);h.InsertNode(2,2);h.InsertNode(2,3);h.Display();Console.WriteLine(h.Size());Console.WriteLine(h.DeleteNode(2));Console.WriteLine(h.Size());Console.WriteLine(h.IsEmpty());Console.WriteLine(h.Get(2));}}
JavaScript
// template for generic typeclassHashNode{constructor(key,value){this.key=key;this.value=value;}}// template for generic typeclassHashMap{constructor(){this.capacity=20;this.size=0;this.arr=newArray(this.capacity);// Initialise all elements of array as NULLfor(leti=0;i<this.capacity;i++){this.arr[i]=null;}// dummy node with value and key -1this.dummy=newHashNode(-1,-1);}// This implements hash function to find index for a keyhashCode(key){returnkey%this.capacity;}// Function to add key value pairinsertNode(key,value){consttemp=newHashNode(key,value);// Apply hash function to find index for given keylethashIndex=this.hashCode(key);// find next free spacewhile(this.arr[hashIndex]!==null&&this.arr[hashIndex].key!==key&&this.arr[hashIndex].key!==-1){hashIndex++;hashIndex%=this.capacity;}// if new node to be inserted// increase the current sizeif(this.arr[hashIndex]===null||this.arr[hashIndex].key===-1){this.size++;}this.arr[hashIndex]=temp;}// Function to delete a key value pairdeleteNode(key){// Apply hash function to find index for given keylethashIndex=this.hashCode(key);// finding the node with given keywhile(this.arr[hashIndex]!==null){// if node foundif(this.arr[hashIndex].key===key){consttemp=this.arr[hashIndex];// Insert dummy node here for further usethis.arr[hashIndex]=this.dummy;// Reduce sizethis.size--;returntemp.value;}hashIndex++;hashIndex%=this.capacity;}// If not found return nullreturnnull;}// Function to search the value for a given keyget(key){// Apply hash function to find index for given keylethashIndex=this.hashCode(key);letcounter=0;// finding the node with given keywhile(this.arr[hashIndex]!==null){if(counter++>this.capacity){// to avoid infinite loopreturn0;}// if node found return its valueif(this.arr[hashIndex].key===key){returnthis.arr[hashIndex].value;}hashIndex++;hashIndex%=this.capacity;}// If not found return nullreturn0;}// Return current sizesizeofMap(){returnthis.size;}// Return true if size is 0isEmpty(){returnthis.size===0;}// Function to display the stored key value pairsdisplay(){for(leti=0;i<this.capacity;i++){if(this.arr[i]!==null&&this.arr[i].key!==-1){console.log(`key = ${this.arr[i].key} value = ${this.arr[i].value}`);}}}}// Driver method to test map classconsth=newHashMap();h.insertNode(1,1);h.insertNode(2,2);h.insertNode(2,3);h.display();console.log(h.sizeofMap());console.log(h.deleteNode(2));console.log(h.sizeofMap());console.log(h.isEmpty());console.log(h.get(2));

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




Next Article
Article Tags :
Practice Tags :

Similar Reads

close