Searching and lookup · Beginner
Hashing for constant-time lookup
Trade memory for time: remember what you have seen in a hash set or map so "have I seen x?" or "where was its complement?" costs expected O(1).
On this page
The idea
The inner loop of many brute-force solutions searches the elements already visited. A hash set answers that search in expected constant time, so the nested loop collapses into a single pass. A hash map does the same when you also need a position or a count.
Three common shapes: membership (duplicates, visited states), complement lookup (find y = target − x among earlier values), and frequency counting (anagrams, majority, sliding-window state).
How to recognise it
- A brute force compares each element with all earlier ones.
- You need to find a partner value for each element (complement, pair, match).
- The answer depends on how often each value occurs, not on order.
- Values are hashable and memory proportional to n is acceptable.
When not to use it
- You need ordered queries (smallest key above x, range of keys): use a sorted structure or sort plus binary search.
- The value range is small and dense: a plain array indexed by value is faster and has no hashing cost.
- Memory is the binding constraint and the input is sorted: two pointers need O(1) extra space.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
# Complement lookup: indices of two values summing to target
index_of = empty map
for i, x in enumerate(a):
j = index_of.get(target - x)
if j is not none: return (j, i)
index_of[x] = i # insert after lookup: x cannot pair with itself
return none
# Frequency
count = empty map
for x in items: count[x] = count.get(x, 0) + 1- Decide what the key is (value, normalised string, tuple of state) and what the value is (index, count, last position).
- Custom key types need consistent equality and hash functions in every language.
Complexity
Time O(n) expected, extra space O(n). Expected O(1) per operation assumes a reasonable hash function and load factor; adversarial or degenerate keys can make individual operations O(n).
Worked examples
Two readings that add to 9 in [4, 7, 5, 2]
4: look for 5, not seen; store 4→0. 7: look for 2, not seen; store 7→1. 5: look for 4, found at 0. Answer (0, 2) after three steps.
Pitfalls
- Inserting before looking up, which lets an element pair with itself.
- Using mutable objects as keys and changing them after insertion.
- Assuming iteration order of a hash map is meaningful.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemTwo readings that add up to a target· beginner · O(n) expected
- ProblemHas any badge been scanned twice?· beginner · O(n) expected
- ProblemSame letters, different order?· beginner · O(n) expected
- ProblemHow many stretches add up to k?· intermediate · O(n) expected
- ProblemThe longest stretch without a repeated letter· intermediate · O(n) expected
- ProblemWhich candidate has more than half the votes?· intermediate · O(n)
- ProblemThe first letter that never repeats· beginner · O(n)
- ProblemGroup words that share their letters· intermediate · O(n · L log L) expected
- ProblemThe k values seen most often· intermediate · O(n + m log k)
Learn the foundations
- ModuleM10 Hash Tables and Sets· intermediate
- VisualizerHash table· put/get/remove expected O(1)
- CollectionDictionary<TKey, TValue>· C#
- Collectiondict· Python
- CollectionHashMap<K, V>· Java
- Collectionstd::unordered_map<Key, T>· C++
- CollectionHashSet<T>· C#
- Collectionset· Python
- CollectionHashSet<E>· Java
- Collectionstd::unordered_set<Key>· C++
Related patterns
- PatternPrefix sums· O(n) build, O(1) per query
- PatternSliding window· O(n)
- PatternTwo pointers· O(n)
References
- Hash table (Wikipedia)
- Dictionary<TKey,TValue> (Microsoft Learn)
- Mapping types: dict (Python documentation)
dsa.pattern.hashing-for-lookup · version 1