Ankit KanojiyaIntermediate
Evergreen guide by Ankit Kanojiya · Intermediate · DSA
Hashing and Hash Maps: The Interview Workhorse
How hash maps deliver average constant-time lookups, why collisions matter, and the problem patterns where a map turns slow solutions into fast ones.
- Hashing
- Hash Maps
- Hash Tables
- Sets
- Collisions
- Frequency Counting
The hash map is the single most useful data structure in coding interviews. It stores key-value pairs and supports insert, lookup, and delete in average O(1) time. Understanding how it achieves that, and where it can degrade, makes it a tool rather than a black box.
How Hashing Works
A hash function maps a key to an integer, which is reduced to an index in a backing array. The value is stored at that index. Lookups rehash the key and go straight to the slot, so the cost does not grow with the number of stored items on average.
Two keys can hash to the same slot. This is a collision, and every real hash map handles it. The two dominant strategies are:
- Separate chaining: each slot holds a small list of entries that landed there. A lookup scans that short list.
- Open addressing: on collision the map probes nearby slots by a fixed rule until a free one is found.
As long as the load factor, the ratio of entries to slots, stays low, chains stay short and operations stay near O(1). When the table fills past a threshold it resizes, allocating a larger array and rehashing every entry. A single insert can therefore occasionally be O(n), but spread across many inserts the amortized cost is still O(1).
The Worst Case
If many keys collide into one slot, lookups degrade to O(n) because the map must scan a long chain. This happens with a poor hash function or with adversarial input crafted to collide. Good general-purpose hash functions and randomized seeds make this rare in practice, but it is why worst-case analysis of hash-based algorithms lists O(n).
Maps Versus Sets
A set stores only keys and answers membership questions. A map stores keys with associated values. Both share the same hashing machinery. Reach for a set when the question is only whether something was seen, and a map when a count, index, or payload must travel with each key.
Pattern: Lookups That Replace a Loop
The canonical example is two-sum on an unsorted array. Brute force checks every pair in O(n squared). A map stores each value as it is seen and asks whether the complement already exists.
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in seen:
return (seen[need], i)
seen[x] = i
return None
Each lookup is O(1) on average, so the whole function is O(n) time and O(n) space. The map trades memory for a dimension of looping.
Pattern: Frequency Counting
Counting occurrences is a natural fit. Grouping anagrams, finding a majority element, or checking whether two strings are anagrams all reduce to comparing counts.
from collections import Counter
def are_anagrams(a, b):
return Counter(a) == Counter(b)
Building each count is O(n) and comparing is O(k) over the distinct characters. Doing the same with sorting would be O(n log n).
Pattern: Grouping by a Derived Key
Many problems cluster items that share a computed property. Anagrams group by their sorted letters:
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
key = tuple(sorted(w))
groups[key].append(w)
return list(groups.values())
The derived key is the signature that collapses equivalent items into one bucket. This shape appears whenever the task is to partition data by some invariant.
Choosing Keys Carefully
Keys must be hashable and compare by value. In most languages immutable types such as numbers, strings, and tuples work; mutable types such as lists do not. A frequent bug is using a mutable object as a key and then mutating it, which corrupts the map because its slot no longer matches its hash.
For composite keys, build a tuple or a canonical string. For counting over a grid, a tuple of coordinates is a clean key.
Space and When to Avoid
Hash maps cost O(n) extra memory, which can matter on large inputs or tight constraints. They also do not maintain order by key. When sorted traversal or range queries are needed, a balanced tree or sorted structure giving O(log n) operations is the better choice. When exact worst-case guarantees are required, the amortized O(1) of a hash map may not be acceptable.
Worked Example
To find the length of the longest consecutive run of integers in an unsorted array, put every value in a set, then for each value that starts a run, meaning its predecessor is absent, count upward.
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # only start at run beginnings
length = 1
while x + length in s:
length += 1
best = max(best, length)
return best
Although it looks nested, each number is visited only inside the run it belongs to, so the total is O(n). The set membership checks are what make it possible. This combination of constant-time lookup and clever iteration is the essence of why hash maps dominate interview solutions.