AlgoMaster Logo

Design HashMap

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Array of List Nodes

Intuition:

The simplest way to implement a hashmap is to use an array where each index holds a linked list of key-value pairs. This method handles collisions by chaining entries together in the form of a linked list. When adding a new entry, we first compute its hash code which gives us the index to put the key-value pair into, and we toggle through the linked list to either update the value or insert a new node.

Code:

2. Double Hashing

Intuition:

By using a secondary hashing technique, we can better address the issue of collision. This involves using an open addressing scheme where slots are utilized in alternative locations if collisions occur. Double hashing uses two hash functions to compute bucket locations.

Code:

3. Binary Search Tree in Buckets

Intuition:

Instead of using linked lists for collisions, we can use a Binary Search Tree (BST). This gives faster operations in a scenario with worst-case time complexity, and makes the performance more stable by reducing the potential of long chains experienced with a basic linked list structure. This approach provides O(log N) operations where N is the number of keys stored in the bucket.

Code: