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
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

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:

Learn the foundations

Related patterns

References

dsa.pattern.hashing-for-lookup · version 1