Hash maps, sets and prefix sums
A hash map gives O(1) average lookup by key, so "have I seen X?", "how many X?" and, with prefix sums, "how many subarrays sum to k?" each take one O(n) pass.
Analogy: A coat check: you hand over a ticket number and get your coat back at once, without searching every hook.
How it works
- Insert, lookup and delete are O(1) average; collisions can make one operation O(n).
- Complement lookup: for each x, check whether
target − xwas already seen. Two-sum becomes O(n). - Prefix sums: the sum of
a[i:j]isP[j] − P[i], one subtraction after O(n) setup. - Count subarrays summing to k with a map of prefix counts seeded with
{0: 1}. - It handles negative numbers, unlike a sliding window, at the cost of O(n) extra memory.
Check yourself
Answer to mark it learned; your answers aren't scored.
Count the subarrays whose sum equals k. The array contains negative numbers. Which approach is correct and O(n)?
Go deeper
Solve it in Python 10
- Group words by their letterseasy
- Two positions that hit a targeteasy
- Strings with the same shapeeasy
- Check a half-filled sudokumedium
- Count runs that sum to kmedium
- Fraction as a repeating decimalmedium
- Longest streak of consecutive numbersmedium
- Pairs with mismatched gapsmedium
- Zero-sum picks from four listsmedium
- Most points on one linehard
Full explanation
A hash map hashes each key to a bucket, so insert, lookup and delete are O(1) on average; collisions can push one operation to O(n). A set is the same with keys only.
Three interview moves:
- Count:
Counter(s)for anagrams, majority element, or the input to a top-k. - Complement lookup: for each
x, ask whethertarget − xwas already seen. Two-sum drops from O(n²) to O(n). - Group by a canonical key:
sorted(word)groups anagrams.
Prefix sums turn a range sum into a subtraction: with P[i] = a[0] + … + a[i−1], the sum of a[i:j] is P[j] − P[i]. To count subarrays summing to k, walk once and add how many earlier prefixes equal prefix − k, keeping prefix counts in a map seeded with {0: 1}. This works with negative numbers, where a Sliding window fails.
Keys must be immutable and hashable: in Python use tuples, not lists.
Code Two-sum, subarray sum equals k, group anagrams
from collections import defaultdict
def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen: # check BEFORE storing: x can't pair with itself
return seen[target - x], i
seen[x] = i
return None
def subarray_sum_k(nums: list[int], k: int) -> int:
counts = {0: 1} # empty prefix: subarrays that start at index 0
prefix = answer = 0
for x in nums:
prefix += x
answer += counts.get(prefix - k, 0) # earlier prefixes p with prefix - p == k
counts[prefix] = counts.get(prefix, 0) + 1
return answer
def group_anagrams(words: list[str]) -> list[list[str]]:
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w) # canonical key
return list(groups.values())Real example
Subarray sum equals k, nums = [1, 2, 3], k = 3. Start with {0: 1}; running prefixes are 1, 3, 6. At prefix 3, 3 − 3 = 0 was seen once → [1, 2]. At prefix 6, 6 − 3 = 3 was seen once → [3]. Answer: 2, in one O(n) pass instead of checking all n(n+1)/2 subarrays.
Trade-offs +3 · −3
+ You gain
- Turns many O(n²) pair searches into one O(n) pass.
- Built in everywhere:
dict,set,Counteranddefaultdictin Python. - Prefix sums answer any range sum in O(1) after O(n) setup.
− You pay
- O(n) extra memory, where sorting plus two pointers needs almost none.
- No order: no "next larger key" or range queries; use a sorted structure for those.
- O(1) is the average only: adversarial keys can force O(n) per operation.
Use it when
"Have I seen it?", counts and frequencies, grouping, pairs that sum to a target, and subarray sums when values can be negative.
Avoid it when
When you need order or ranges (sorted list, heap, tree), when O(1) extra space is required, or when the input is already sorted: two pointers is simpler.
Numbers to know 4
- Python
dict/set: get, set, delete andinare O(1) average, O(n) worst case when keys collide. - Python salts
strandbyteshashes per process by default (since 3.3) to block hash-flooding denial of service. - Java 8
HashMapturns crowded buckets into balanced trees: worst case O(log n) instead of O(n) for comparable keys. - Two-sum: O(n²) brute force → O(n) time and O(n) space with a map.
Common pitfalls 4
- Storing before checking in two-sum: an element pairs with itself when
x == target − x. - Forgetting the
{0: 1}seed: you miss every subarray that starts at index 0. - Using a list as a key: lists are unhashable; convert to a tuple or a string.
- Using a sliding window for "sum equals k" with negatives: shrinking no longer lowers the sum.
Interview questions 3
Answer out loud first, then reveal.
How do you recognize a hash map problem?Show answer
Three signals. The brute force compares every pair, and one side is computable from the other: "find x with x + y = target" means look up target − y. The problem asks about counts, duplicates or frequencies. Or items must be grouped by an equivalence, like anagrams, so I build a canonical key. If the input is sorted or O(1) space is required, I consider two pointers instead.
Count subarrays with sum k when numbers can be negative.Show answer
A sliding window fails: adding a negative number lowers the sum, so shrinking isn't monotonic. I use prefix sums: the subarray after index i up to j sums to k exactly when P[j] − P[i] = k. One pass with a map from prefix value to how often it occurred, seeded with {0: 1} for subarrays starting at index 0. O(n) time, O(n) space.
What's the worst case of a hash map, and does it matter?Show answer
O(n) per operation when keys collide, so a loop becomes O(n²). With ordinary keys it's rare, but attackers can choose colliding keys: the 2011 hash-flooding advisories showed crafted POST requests pinning web servers' CPUs. Python now salts string hashes and Java 8 turns long buckets into trees. In interviews I say "O(1) average" and raise it when inputs are untrusted.