Recognize it when A brute-force inner loop repeatedly searches for a value, complement, identifier, or previously seen state.
Checking your account…
Hash Map Code Labs
Mental Model
A hash map stores an association from a key to a value. The key is how you ask a
question. The value is the answer you want to retrieve later.
For an interview problem, the most important design decision is not the dictionary syntax. It is
the meaning of the association:
Question you need to answer
Useful association
Have I seen this number before, and where?
number -> earlier_index
How often has this token appeared?
token -> count
Which records share the same signature?
signature -> list_of_records
What result did this subproblem produce?
state -> computed_result
Write that relationship down before coding. If the key or value changes meaning halfway through
the loop, the implementation becomes difficult to reason about and hidden edge cases follow.
Python’s dict is the general-purpose mapping type used for these associations. It preserves
insertion order, but exact-key lookup is still the central capability. Verify the language contract
in the Python documentation(opens in a new tab).
Do not choose a dictionary only because you want the first, smallest, or next key. Those are
different query requirements.
Python Dict Operations
Create a dictionary with a literal, a constructor, or a comprehension:
Construct dictionaries deliberately
Reference
scores = {"Ada": 92, "Grace": 98}
empty = dict()
squares = {number: number * number for number in range(5)}
Practice
Create scores for Ada and Grace, an empty dictionary, and a square-number mapping with a dictionary comprehension.
Public tests
Build the requested dictionaries
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Construct dictionaries deliberately
scores = {"Ada": 92, "Grace": 98}
empty = dict()
squares = {number: number * number for number in range(5)}
Read, insert, update, test membership, and delete with operations that state your intent:
Iterating a dictionary produces keys. Use .items() when both parts of the association matter:
Iterate keys and key-value pairs
Reference
scores = {"Ada": 95, "Grace": 98}
names = []
pairs = []
for name in scores:
names.append(name)
for name, score in scores.items():
pairs.append((name, score))
Practice
Collect dictionary keys through normal iteration, then collect matching name and score pairs through items().
Public tests
Keep keys separate from key-value pairs
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Iterate keys and key-value pairs
scores = {"Ada": 95, "Grace": 98}
names = []
pairs = []
for name in scores:
names.append(name)
for name, score in scores.items():
pairs.append((name, score))
Do not change dictionary size during a traversal of its live views. Iterate over a snapshot when
deletion is intentional:
Delete from a safe key snapshot
Reference
scores = {"Ada": 92, "Grace": 98, "Linus": 87}
for name in list(scores):
if scores[name] < 90:
del scores[name]
Practice
Remove scores below 90 while preserving the qualifying entries by iterating a snapshot instead of a live dictionary view.
Public tests
Delete only low scores without a live-view mutation
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Delete from a safe key snapshot
scores = {"Ada": 92, "Grace": 98, "Linus": 87}
for name in list(scores):
if scores[name] < 90:
del scores[name]
Choose the Missing-Key Behavior Deliberately
These tools solve related but different problems:
Tool
Missing key behavior
Best fit
mapping[key]
Raises KeyError
Absence violates the contract
mapping.get(key, default)
Returns default without insertion
Optional read
mapping.setdefault(key, default)
Inserts and returns default
Small accumulation task
defaultdict(factory)
Bracket access creates a factory value
Repeated grouping or accumulation
Counter(iterable)
Missing counts read as zero
Frequency and multiset work
setdefault is concise for a small grouping loop:
Group values with setdefault
Reference
words = ["tea", "eat", "tan"]
groups = {}
for word in words:
signature = "".join(sorted(word))
groups.setdefault(signature, []).append(word)
grouped = list(groups.values())
Practice
Group words by their sorted-character signature with setdefault so each signature receives a growing list.
Public tests
Put anagrams in the same list
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Group values with setdefault
words = ["tea", "eat", "tan"]
groups = {}
for word in words:
signature = "".join(sorted(word))
groups.setdefault(signature, []).append(word)
grouped = list(groups.values())
For a larger grouping routine, defaultdict makes the accumulation rule explicit:
Group values with defaultdict
Reference
from collections import defaultdict
words = ["tea", "eat", "tan"]
groups = defaultdict(list)
for word in words:
signature = "".join(sorted(word))
groups[signature].append(word)
grouped = list(groups.values())
Practice
Use defaultdict(list) to make the repeated grouping rule explicit while keeping equivalent words under one signature.
Public tests
Create a list only when a signature is used
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Group values with defaultdict
from collections import defaultdict
words = ["tea", "eat", "tan"]
groups = defaultdict(list)
for word in words:
signature = "".join(sorted(word))
groups[signature].append(word)
grouped = list(groups.values())
Separate Encounter Order from Missing Values
Predict the key order after updating Ada, then after deleting and reinserting it. Updating a value preserves its existing position; reinserting a deleted key adds a new position at the end. This is encounter order, not sorted order. Also predict whether the last two reads can distinguish a stored None from an absent key. Execute the statements in sequence.
Line
Python statement
Observation
1
scores = {"Ada": 0, "Lin": None}
Store both a zero and an explicit missing-value marker.
2
scores["Ada"] = 5
Update without moving the key.
3
print(list(scores))
Inspect existing encounter order.
4
scores.pop("Ada")
Remove the old key position.
5
scores["Ada"] = 0
Reinsert at the end.
6
print(list(scores))
Inspect the new encounter order.
7
print(scores.get("Ada"), scores.get("Kai"))
Present zero differs from absent None.
8
print(scores.get("Lin"), scores.get("Kai"))
Both reads return None.
9
print("Lin" in scores, "Kai" in scores)
Membership distinguishes presence.
Expected printed output:
Print
Output
1
['Ada', 'Lin']
2
['Lin', 'Ada']
3
0 None
4
None None
5
True False
A zero score is present even though it is false in a condition. get returns the same None for the stored Lin value and the absent Kai key; membership separates them. Do not write if scores.get(name) when the question is whether the key exists. Use name in scores, or a unique sentinel when one lookup must distinguish absence from every allowed value. In interview code, define the value domain first: can zero, None, or an empty collection be a real result? Insertion order can preserve encounter order, but it cannot answer a smallest-key query.
Practical Code Patterns
Frequency Map
Start with the manual form to connect a missing key to a zero prior count. Before each update, the mapping counts exactly the words already processed; adding one extends that prefix. A stored zero would still be a present key, so presence and count are separate questions:
Build a frequency map manually
Reference
def count_words(words):
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
counts = count_words(["red", "blue", "red", "green"])
Practice
Implement count_words with get so every word increments its own count without a separate membership branch.
Public tests
Count repeated and unique words
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Build a frequency map manually
def count_words(words):
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
counts = count_words(["red", "blue", "red", "green"])
Trace a Missing Count Becoming an Accumulated Count
Call the existing manual frequency Lab with one repeated token. Follow both reads of red: the first optional read returns zero without insertion, while the later read retrieves the accumulated count. The assignment is the deliberate state change.
print(count_words(['red', 'blue', 'red'])) followed by print(count_words([]))
Step
Executed statement
State
Why
1
counts = {}
counts = {}
No words have been processed, so no associations exist.
2
counts[word] = counts.get(word, 0) + 1
word = 'red'; prior = 0; counts = {'red': 1}
The fallback supplies the empty-prefix count; assignment inserts the key.
Reading the stored value preserves earlier occurrences rather than resetting them.
5
return counts
result = {'red': 2, 'blue': 1}
The full prefix is now the whole input; the empty call returns an empty mapping.
Print
Output
1
{'red': 2, 'blue': 1}
2
{}
The invariant is local and checkable: after each word, its count increases once and every other count stays fixed. Dictionary encounter order makes this printed result deterministic, but the counts, rather than that order, are the purpose of the mapping.
Use Counter when the problem simply needs standard frequency behavior:
The dictionary mechanics stay simple. The interview insight is choosing a stable signature that
places equivalent inputs in the same group:
Group anagrams by a tuple key
Reference
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
signature = tuple(sorted(word))
groups[signature].append(word)
return list(groups.values())
groups = group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
Practice
Use a hashable sorted-character tuple as the key so each anagram group keeps the original words together.
Public tests
Use a stable, hashable signature for each group
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Group anagrams by a tuple key
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
signature = tuple(sorted(word))
groups[signature].append(word)
return list(groups.values())
groups = group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"])
The tuple is hashable. A list containing the same characters would not be a valid key.
One-Pass Complement Lookup
Find a complement in one pass
Reference
def two_sum(values, target):
seen = {} # value -> earlier index
for index, value in enumerate(values):
complement = target - value
if complement in seen:
return [seen[complement], index]
seen[value] = index
return []
Practice
Check the complement before storing the current value so the map contains only earlier indices and never reuses an index.
Public tests
Return two distinct original indices
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Find a complement in one pass
def two_sum(values, target):
seen = {} # value -> earlier index
for index, value in enumerate(values):
complement = target - value
if complement in seen:
return [seen[complement], index]
seen[value] = index
return []
The order is the proof. Before each lookup, seen contains only earlier indices. A match therefore
uses two different positions, and the returned indices remain in original input order.
How Lookup Works
At the abstract data-structure level, a lookup follows three ideas:
Python obtains hash and equality behavior from the key.
The mapping uses that information to narrow the search for a matching key.
If an equal key is present, the mapping returns the associated value.
Different keys can produce the same hash. A correct mapping still uses equality to distinguish
them. This is why a hash match alone cannot prove that two keys are the same.
The key must keep stable hash and equality behavior while stored. Immutable built-ins such as
strings, numbers, and tuples of hashable values are common keys. Mutable containers such as lists,
dictionaries, and sets are not hashable.
This guide intentionally stops at the language-level contract. You do not need CPython table
layout details to choose a dictionary, write a correct invariant, or explain average complexity in
a coding round.
Interview Recognition Patterns
Look for the inner search in a brute-force solution. If every iteration scans earlier values to
answer one of these questions, a dictionary may replace that scan:
Where did I see this value?
How many times has this value appeared?
Which group owns this item?
Have I already computed this state?
What earlier prefix would complete the current target?
Then define the association in one sentence and decide when it becomes valid. That timing often
separates a correct solution from a plausible one.
When the prompt asks only whether something exists, compare a set. When it requires a value, count,
index, group, or computed result, a dictionary is usually the clearer model.
Templates To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Count and group with a dictionary
Count it; same key, same bucket.
You need how often each item appears, or you must put items that share a property in the same bucket.
Trigger words
anagram
frequency
count occurrences
group by
most common
same letters, any order
from collections import Counter, defaultdict
def count_and_group(words):
count = Counter(words) # word -> how many times
groups = defaultdict(list) # key -> words that share it
for word in words:
key = ''.join(sorted(word)) # the knob: what makes two items "the same"
groups[key].append(word)
return count, list(groups.values())
Spot it when
Words in any order should be treated as the same (anagrams).
The answer depends on frequencies, not positions.
Remember
Choosing the key is the whole problem: sorted letters, a tuple of 26 counts, a lowercased word.
Counter(a) == Counter(b) compares two multisets in O(n).
How problems bend it
Top k most frequent: Count first, then sort the (item, count) pairs by count or use a heap or bucket list.
Compare two strings: Build one Counter per string and compare them.
Hash table with buckets
Hash to a bucket, scan the bucket, update or append.
You must build a hash map or hash set yourself, without dict or set.
Trigger words
design hashmap
design hashset
no built-in dict
buckets + chaining
class BucketMap:
def __init__(self, size=1000):
self.size = size
self.buckets = [[] for _ in range(size)] # each bucket holds [key, value] pairs
def put(self, key, value):
bucket = self.buckets[key % self.size]
for pair in bucket:
if pair[0] == key:
pair[1] = value # key exists: update it
return
bucket.append([key, value]) # new key: append it
def get(self, key):
for k, v in self.buckets[key % self.size]:
if k == key:
return v
return -1
Spot it when
'Design a HashMap / HashSet' without built-in hash tables.
Remember
Different keys can land in the same bucket (a collision), so always compare the exact key.
With n keys spread over size buckets, each operation scans about n / size items.
How problems bend it
Hash set: Store only keys: add appends the key if it is missing, contains scans the bucket.
Remove a key: Find the key's position in its bucket and pop it.
Python Version Note
Python 3.7+
Dictionary insertion order is a language guarantee. Updating a key keeps its position, while deleting and reinserting it places it at the end.
setdefault inserts the supplied list even when an optional read only needs to report absence. The assignment receives an empty list while group membership has also changed.
Prevent it: Use get for a read-only presence probe; reserve setdefault for deliberate accumulation.