Skip to contentKEEP THE CRAFTTHE SANCTUARY

Hashing

Store an exact key-to-summary meaning to replace repeated scans with expected fast lookup. Separate equality from collisions, membership from value truthiness, and prior-input state from the current insertion.

3 practice exercises23 interview problems

Recognize it when Repeated membership, complement or frequency queries revisit earlier items.

Checking your account…

Hashing Code Labs

Trade Space for Direct Access

Hashing stores a summary under a key so future work can jump directly to relevant prior state. That extra O(n) space often replaces an O(n) inner scan with average O(1) lookup, producing an O(n) one-pass solution.

Design the Stored Meaning

Name both key and value before coding: value → latest index, prefix sum → frequency, normalized signature → group. The invariant should say exactly which processed items the table represents. Lookup before insertion when the current item cannot pair with itself.

Build a Frequency State

Reference
def frequency_state(values):
    counts = {}
    for value in values:
        counts[value] = counts.get(value, 0) + 1
    return counts
Practice

Implement frequency_state(values). Return a dictionary mapping each hashable value to its frequency without mutating values.

Public tests

  • Store the intended summary

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build a Frequency State

def frequency_state(values):
    counts = {}
    for value in values:
        counts[value] = counts.get(value, 0) + 1
    return counts

Accumulate the Intended Frequency Summary

Predict the existing frequency Lab before running it. The printed dictionary follows first-insertion order, while the values count every processed occurrence.

Step Executed statement State Why
Create state counts = {} counts={} before items No key has been observed yet.
First x counts[value] = counts.get(value, 0) + 1 counts={"x":1} A missing count is zero, then the current occurrence contributes one.
First y counts[value] = counts.get(value, 0) + 1 counts={"x":1,"y":1} A new independent key does not overwrite the x summary.
Repeated x counts[value] = counts.get(value, 0) + 1 counts={"x":2,"y":1} Update the same key; its insertion position remains before y.
Empty input return counts {} No iterations leave the correct empty frequency mapping.
Print Output
print(frequency_state(["x","y","x"])) {'x': 2, 'y': 1}
print(frequency_state([])) {}

The pair Lab instead stores the first index for each value and stops at the first current index admitting an earlier complement. Its query-before-insert ordering is a correctness condition, not a style preference.

Find Two-Sum Indices

Reference
def two_sum_indices(values, target):
    seen = {}
    for index, value in enumerate(values):
        complement = target - value
        if complement in seen:
            return [seen[complement], index]
        if value not in seen:
            seen[value] = index
    return []
Practice

Implement two_sum_indices(values, target). Return the first [earlier_index, current_index] found in a left-to-right scan, or [] when no pair exists. An index cannot be reused.

Public tests

  • Lookup before insertion and avoid reuse

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Two-Sum Indices

def two_sum_indices(values, target):
    seen = {}
    for index, value in enumerate(values):
        complement = target - value
        if complement in seen:
            return [seen[complement], index]
        if value not in seen:
            seen[value] = index
    return []

Handle Collisions Through Equality

Equal hashable keys must have equal hashes; equal hashes do not prove equal keys. Dictionaries resolve collisions with equality checks. Lists and dictionaries are unhashable. A tuple is hashable only when every element is hashable, so tuple([1,2]) works but a tuple containing a list does not.

Choose Hashing or Sorting

Choose hashing for direct membership, counting, or complement lookup when order is irrelevant. Choose sorting when adjacency, ranks, deterministic traversal, or two-pointer movement matters. Hash operations are average O(1), not a universal worst-case guarantee, and the table costs additional space.

Explain It in an Interview

Say: “My dictionary maps this key to this precise summary of earlier items. I query before updating, so I cannot reuse the current index.” State average O(n) time, O(n) space, and the hashable-key assumption. The Python dictionary reference(opens in a new tab) defines lookup behavior; Binary Subarrays With Sum(opens in a new tab) demonstrates prefix-state counting.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Hash map lookup

Watch: Hash map lookup in 4 minutes, with Quill.

Look back first, then store yourself.

You need to know instantly whether a value (or its partner) appeared earlier in the input.

Trigger words

  • two sum
  • unsorted + pair sum
  • seen before
  • contains duplicate
  • first repeated
  • complement
  • consecutive sequence
def find_pair(nums, target):
    seen = {}  # value -> index
    for i, num in enumerate(nums):
        need = target - num
        if need in seen:          # 1. look up first
            return [seen[need], i]
        seen[num] = i             # 2. then store
    return []

Spot it when

  • The problem asks for a pair, a duplicate, or 'have I seen this before?'
  • A brute-force answer would compare every pair in O(n^2).

Remember

  • The dictionary only holds items before the current one, so an item never pairs with itself.
  • Store whatever you must return later: an index, a count, or a position.

How problems bend it

  • Only need to know if a value repeats: Use a set instead of a dictionary: if num in seen, return True; else seen.add(num).
  • Need the last or first position of each value: Overwrite seen[num] = i to keep the latest, or only set it when num is not in seen to keep the first.
  • Clone a list or graph with extra links: First map every old node to a new copy, then wire each copy's links through the map: copies[old.next], copies[old.random].

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Dictionary frequency passExpected O(n)O(n^2)Expected constant table operations for bounded-cost keys; pathological collisions can require linear scans.
One separate-chain lookupO(b)O(b)b is selected bucket length, assuming constant-cost equality.

Space

O(k) entries for k distinct keys; a one-bucket query needs O(1) extra state.

Assumptions

  • Long tuple or string key creation and first hashing may cost key length.
  • Python dictionaries preserve insertion order, but that order is not sorted-key order.

Invariants Worth Saying Aloud

  1. The key and value have stated meanings, such as value-to-count or value-to-first-index.
  2. Equal keys have equal hashes; unequal keys can still collide and require equality resolution.
  3. The stored prefix excludes or includes the current item according to the reuse contract.

When To Use Or Avoid Hashing

Use It When

  • Use dict or set when hashable keys and expected lookup costs fit the constraints.
  • For pairs, query prior state before inserting the current item when index reuse is forbidden.

Choose Another Tool When

  • Use sorting when rank, ordered traversal or adjacent comparison supplies the required structure.
  • Mutable list/dict keys are not hashable; immutable containers are hashable only when their contents are.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Equating a bucket collision with a key match

Keys 1 and 4 share modulo-3 bucket 1. Returning its first entry retrieves the wrong key.

Prevent it: Compare the full stored key inside the selected bucket.

Avoid

answer=bucket[0][1]

Use instead

answer=next((value for stored,value in bucket if stored==key),None)

Inserting before a no-reuse lookup

For one value 5 and target 10, inserting 5 first makes its own complement appear present.

Prevent it: Query the earlier prefix before adding the current item.

Avoid

seen[value]=index
found=(target-value) in seen

Use instead

found=(target-value) in seen
seen[value]=index

Confusing a stored zero with an absent key

A value of zero is a legitimate stored result. bool(table.get(key)) answers truthiness, not membership.

Prevent it: Test key in table when the question is presence.

Avoid

present=bool(table.get(key))

Use instead

present=key in table

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.