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.
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.
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
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Hashing proof does not depend on a minor Python release.