HashMap Implementation from Scratch in DSA Java - Time & Space Complexity
When building a HashMap from scratch, it is important to understand how fast it can add and find items.
We want to know how the time to do these operations changes as the number of items grows.
Analyze the time complexity of the following code snippet.
public class SimpleHashMap {
private static class Node {
String key;
String value;
Node next;
Node(String key, String value) {
this.key = key;
this.value = value;
}
}
private Node[] buckets = new Node[16];
public void put(String key, String value) {
int index = Math.abs(key.hashCode()) % buckets.length;
Node head = buckets[index];
for (Node curr = head; curr != null; curr = curr.next) {
if (curr.key.equals(key)) {
curr.value = value;
return;
}
}
Node newNode = new Node(key, value);
newNode.next = head;
buckets[index] = newNode;
}
}
This code adds a key-value pair to a simple HashMap using an array of linked lists for buckets.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through linked list nodes in a bucket to check for existing key.
- How many times: Up to the number of nodes in that bucket, which depends on collisions.
As more items are added, the number of nodes in each bucket can grow if many keys collide.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 to 2 checks per put (few collisions) |
| 100 | About 6 to 7 checks per put if collisions increase |
| 1000 | Up to 60+ checks per put if many keys collide in same bucket |
Pattern observation: If keys spread evenly, checks stay low; if many collide, checks grow linearly with n.
Time Complexity: O(n) in worst case
This means adding or finding a key can take time proportional to the number of items if many keys collide.
[X] Wrong: "HashMap operations always take the same short time no matter what."
[OK] Correct: If many keys end up in the same bucket, the linked list grows and operations slow down.
Understanding how collisions affect HashMap speed shows you know the trade-offs in data structures.
"What if we replaced the linked list with a balanced tree for buckets? How would the time complexity change?"
Practice
HashMap in Java?Solution
Step 1: Understand HashMap functionality
A HashMap stores data as key-value pairs allowing quick access by key.Step 2: Compare with other data structures
Unlike sorted or stack structures, HashMap focuses on fast lookup, not order or uniqueness of values alone.Final Answer:
To store key-value pairs for fast lookup -> Option AQuick Check:
HashMap = key-value fast access [OK]
- Confusing HashMap with TreeMap (sorted)
- Thinking HashMap stores only unique values
- Mixing HashMap with stack or queue behavior
Solution
Step 1: Check generic syntax for HashMap
Java requires specifying key and value types inside angle brackets <Key, Value>.Step 2: Identify correct generic declaration
HashMap map = new HashMap(); uses full generic syntax for both declaration and instantiation, which is correct in Java before version 7.Final Answer:
HashMap map = new HashMap(); -> Option DQuick Check:
Full generic syntax = HashMap map = new HashMap(); [OK]
- Omitting generic types on instantiation (Option A is Java 7+ syntax)
- Using only one generic type (Option D is invalid)
- Not using generics at all (Option C is raw type)
public void put(K key, V value) {
int index = key.hashCode() % capacity;
if (buckets[index] == null) {
buckets[index] = new Node(key, value);
} else {
Node current = buckets[index];
while (current.next != null) {
if (current.key.equals(key)) {
current.value = value;
return;
}
current = current.next;
}
current.next = new Node(key, value);
}
}What happens if we insert two keys with the same hashCode but different values?
Solution
Step 1: Understand collision handling in code
If bucket is occupied, code traverses linked nodes to check keys and appends new node if key not found.Step 2: Analyze insertion of different keys with same hash
Since keys differ but hash is same, new node is added at end of linked list, preserving both pairs.Final Answer:
Both key-value pairs are stored in a linked list at the same bucket -> Option CQuick Check:
Collision handled by chaining = Both key-value pairs are stored in a linked list at the same bucket [OK]
- Assuming second key overwrites first without key match
- Thinking collision causes error
- Ignoring linked list chaining for collisions
public void put(K key, V value) {
int index = key.hashCode() % capacity;
if (buckets[index] == null) {
buckets[index] = new Node(key, value);
} else {
Node current = buckets[index];
while (current != null) {
if (current.key.equals(key)) {
current.value = value;
return;
}
current = current.next;
}
current.next = new Node(key, value);
}
}What is the error in this code?
Solution
Step 1: Analyze the while loop condition
The loop runs while current != null, so after loop current becomes null.Step 2: Check where new node is added
After loop, code tries current.next = new Node(...), but current is null causing NullPointerException.Step 3: Correct loop condition
Changing loop to while (current.next != null) stops at last node, allowing safe addition at current.next.Final Answer:
The loop condition should be while (current.next != null) instead of while (current != null) -> Option AQuick Check:
Loop must stop at last node to add new node [OK]
- Using current != null causes NullPointerException on insertion
- Incorrect modulo operation for bucket index
- Using == instead of equals() for key comparison
Assume bucket index = hashCode % capacity and each bucket holds a linked list of nodes.
Choose the correct bucket contents representation (keys only):
Solution
Step 1: Calculate bucket index for each key
Using index = hashCode % 4:
2 % 4 = 2
6 % 4 = 2
10 % 4 = 2
14 % 4 = 2Step 2: Re-examine calculation carefully
Actually:
2 % 4 = 2
6 % 4 = 2
10 % 4 = 2
14 % 4 = 2
All keys map to bucket 2, so all should be in bucket 2 linked list.Step 3: Check options for matching bucket 2 content
Bucket 0: null
Bucket 1: null
Bucket 2: 2 -> 6 -> 10 -> 14
Bucket 3: null shows all keys in bucket 2 linked list, which matches calculation.Step 4: Verify other buckets are null
Other buckets 0,1,3 are null as no keys map there.Final Answer:
Bucket 0: null
Bucket 1: null
Bucket 2: 2 -> 6 -> 10 -> 14
Bucket 3: null -> Option BQuick Check:
All keys % 4 = 2, so bucket 2 holds all [OK]
- Miscomputing modulo operation
- Distributing keys incorrectly across buckets
- Assuming keys spread evenly without modulo check
Ready to prove it?
Pass the test and this pattern moves unknown
