HashMap in Data Structures: Operations, Examples and Complexity
How a HashMap works: hashing, buckets, collisions and O(1) average operations, with Python code and the interview problems it solves.
A HashMap, also called a hash map or hash table, is a data structure that stores key-value pairs and uses a hash function to turn each key into an array index, so a value can be found without scanning. Insert, lookup and delete take O(1) time on average. When two keys land on the same index, the map resolves the collision.
Key takeaways
- A hash function maps a key to a bucket index. The same key always gives the same index.
- Collisions are normal. The two standard fixes are chaining (a list per bucket) and open addressing (probe for the next free slot).
- Average cost is O(1) for put, get and remove. Worst case is O(n) if many keys collide, though Java 8 onward can reduce this by converting long buckets to balanced trees.
- Many interview problems (two sum, anagram grouping, subarray sum) become linear once you add a map.
On this page:
- What a HashMap stores
- Hashing, buckets and collisions
- Operations and complexity
- Common interview applications
| Operation | Average | Worst case | Note |
|---|---|---|---|
| put (insert or update) | O(1) | O(n) | Occasional resize copies all entries |
| get (lookup by key) | O(1) | O(n) | Worst case when most keys share a bucket |
| remove | O(1) | O(n) | Same bucket search as get |
| Search by value | O(n) | O(n) | The map is indexed by key, not value |
| Iterate all entries | O(n) | O(n) | Classic hash tables do not sort keys |
What a HashMap stores
A HashMap stores unique keys, each paired with a value, and finds a value by its key rather than its position. An array is indexed by position; a HashMap is indexed by key.
Think of a phone contacts list: you type a name and get the number without scrolling through every contact. In code:
phone = {}
phone["Asha"] = "98xxxxxx01"
phone["Ravi"] = "98xxxxxx02"
print(phone["Asha"]) # 98xxxxxx01
print("Meena" in phone) # False
In Java the same idea is HashMap<String, String>. In Python it is a dict, which keeps insertion order from Python 3.7 onward. In an unsorted array, finding a value takes O(n); even a sorted array needs O(log n) with binary search. A HashMap targets O(1) on average, which is why it is the first structure to try when a problem asks "have I seen this before?". For the array comparison, see array data structure explained.
Hashing, buckets and collisions
The map keeps an internal array of buckets. A hash function converts the key to an integer, and that integer modulo the array size picks the bucket.
index = hash(key) % number_of_buckets
In Java, Math.floorMod(key.hashCode(), n) keeps the index non-negative because hashCode can be negative. A good hash function spreads keys evenly.
A collision is when two different keys map to the same bucket. Trace with 8 buckets and integer keys (illustrative; real maps hash differently): 10 % 8 = 2, 18 % 8 = 2, 26 % 8 = 2. All three land in bucket 2.
| Method | How it handles a collision | Trade-off |
|---|---|---|
| Chaining | Each bucket holds a list of entries | Simple; long lists slow lookups |
| Open addressing | Probe to the next free slot in the array | Less memory per entry; needs low load and careful deletes |
Here is a minimal chaining map you can run:
class ChainedMap:
def __init__(self, size=8):
self.buckets = [[] for _ in range(size)]
def _index(self, key):
return hash(key) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self._index(key)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
def get(self, key, default=None):
for k, v in self.buckets[self._index(key)]:
if k == key:
return v
return default
m = ChainedMap()
for k in (10, 18, 26):
m.put(k, str(k))
print(m.buckets[2]) # [(10, '10'), (18, '18'), (26, '26')]
print(m.get(18)) # 18
Real implementations track a load factor (entries divided by buckets). Java's HashMap resizes by doubling when the default load factor of 0.75 is crossed, then redistributes entries. That occasional copy is why a single insert can take longer even though the average stays O(1).
Operations and complexity
The three core operations are put, get and remove. Each hashes the key, goes to one bucket and searches only that bucket, which is why they take O(1) on average.
Walk through get(18) in the map above: hash 18 to bucket 2, scan the three entries there, find key 18 on the second and return its value. If the map had 1,000 keys spread evenly over 1,024 buckets, each bucket would hold about one entry. If all 1,000 landed in one bucket, get would scan 1,000 entries, which is the O(n) worst case.
- Keys must be hashable and stable. A key whose hash changes after insertion becomes unfindable. That is why Python lists cannot be dict keys but tuples can.
- Equal keys must give equal hashes. In Java, override hashCode whenever you override equals.
- Order is not a feature. Use a tree-based map if you need keys sorted.
- Space: O(n) for n entries, plus spare buckets.
Our time complexity and Big O guide explains how to state average and worst case in an interview.
Common interview applications
Use a HashMap when you need fast "seen before?" checks, counts or lookups by key. These patterns cover most interview questions.
Two sum: find two numbers that add to a target, in one pass.
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
Brute force checks every pair in O(n squared); the map makes it O(n) time and O(n) space.
Subarray sum equals k: count subarrays with a given sum using prefix sums.
def count_subarrays(nums, k):
seen = {0: 1}
total = count = 0
for x in nums:
total += x
count += seen.get(total - k, 0)
seen[total] = seen.get(total, 0) + 1
return count
print(count_subarrays([1, 1, 1], 2)) # 2
- Frequency counting: first non-repeating character, top-k words.
- Grouping: group anagrams by a sorted-letters key.
- Duplicates and membership: contains duplicate, intersection of two lists.
- Caching: remember results to avoid repeated work, as in dynamic programming.
For more of this kind, try sliding window and two pointers patterns (they often pair with a map), and the most asked DSA interview questions.
Next step
Implement the ChainedMap from memory, then solve two sum and subarray sum without looking. If you want structured AI and machine learning training where data structures still show up in interviews, see the AI and ML certification from Vishlesan i-Hub, IIT Patna, and check the current batch and eligibility on the programme page.
Frequently asked questions
What is a HashMap in a data structure?
A HashMap stores key-value pairs and uses a hash function to turn each key into an array index, so values can be found by key in O(1) time on average, without scanning the whole collection.
What is a hash collision?
A collision happens when two different keys produce the same bucket index. The map resolves it with chaining, which keeps a list per bucket, or open addressing, which probes for another free slot.
What is the time complexity of a HashMap?
Put, get and remove are O(1) on average and O(n) in the worst case when many keys collide. Searching by value is O(n), because the map is indexed by key.
What is the difference between a HashMap and an array?
An array is indexed by position and is fast when you know the index. A HashMap is indexed by key, so you can look up a value by a name or ID without knowing where it is stored.
Why are HashMaps common in coding interviews?
They turn many O(n squared) searches into O(n) by remembering what you have seen. Two sum, counting, grouping and prefix-sum problems all use this pattern.