Chapter 3: Arrays and hashing
Most array problems reduce to a single question: how do I avoid the brute-force scan? The obvious solution to “find two numbers that sum to a target” or “does this array contain a duplicate?” compares every element with every other. The answer is almost always a hash map or hash set, which trades memory for time by giving expected lookups. Instead of asking “which earlier element pairs with this one?” by scanning, you ask “have I already seen what I need?” in constant time.
Concepts from other sections (2)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Binary search tree (BST): a binary tree in which every node’s value is greater than every value in its left subtree and less than every value in its right subtree, so a search follows one root-to-leaf path and an in-order traversal yields the values in sorted order. Read more: Chapter 7: Trees
- Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence in Mathematics
This chapter opens the book because nearly every efficient solution that follows uses the same move somewhere. It presents five patterns built on it (complement lookup, frequency counting, using indices as hash keys, prefix sums, and set membership), gives a template for each, and then walks through four classic problems whose JavaScript solutions sit next to this text.
Learning objectives
- Recognize when a pair, group, or frequency problem can be solved in with a hash map or set.
- Apply the complement-lookup, frequency-counting, and prefix-sum templates.
- Use array indices as an implicit hash when values are bounded, to reach extra space.
- Choose between brute force, sorting, hashing, and index marking from their time and space costs.
Before you begin
Section titled “Before you begin”You need to be comfortable with loops and arrays in JavaScript or Python. It helps to know what a hash table does and why its lookups are constant time on average; Modular arithmetic, hashing, and PCG32 in Mathematics covers the math, and the Swiss table in this book’s systems chapter builds a production hash map.
Complement lookup with a hash map
Section titled “Complement lookup with a hash map”Use this pattern when you need to find pairs or groups that satisfy a relationship such as a sum, difference, or product. Walk the array once; for each element, compute the partner it would need, check whether that partner is already in the map, and only then record the current element:
seen = {}for each element: complement = target - element if complement in seen: return answer seen[element] = indexInstead of checking every pair in , you check “have I already seen what I need?” in . Recording the element after the check matters: it stops an element from pairing with itself. The pattern solves Two Sum, Two Sum II, 4Sum II, and Subarray Sum Equals K.
Frequency counting
Section titled “Frequency counting”Problems about duplicates, anagrams, majority elements, or “most or least frequent” all start by counting. Build a map from value to count in one pass, then answer the question from the map:
freq = {}for each element: freq[element] = freq.get(element, 0) + 1# Then query the frequency mapContains Duplicate, Valid Anagram, Group Anagrams, Top K Frequent Elements, and Majority Element are all instances.
Indices as hash keys
Section titled “Indices as hash keys”When the values are bounded, for example all in the range , the array itself can serve as the hash table, and you get extra space. Mark value as seen by negating the entry at index ; afterwards, a positive entry at index means never appeared:
for each element: index = abs(element) - 1 nums[index] = -abs(nums[index]) # mark as seen# Positive values at index i mean i+1 is missingMissing Number, Find All Duplicates, and First Missing Positive use this idea, as do related tricks that let the indices stand in for the values you expect to see.
Prefix sums
Section titled “Prefix sums”Range sums, subarray sums, and “number of subarrays with sum ” yield to prefix sums. A subarray from to sums to exactly when the running sum at minus the running sum before is , so you keep a map from each running sum to how often it has occurred and look up running_sum - k:
prefix = {0: 1} # sum -> countrunning_sum = 0for each element: running_sum += element if running_sum - k in prefix: count += prefix[running_sum - k] prefix[running_sum] = prefix.get(running_sum, 0) + 1The entry {0: 1} accounts for subarrays that start at the beginning. The same running-aggregate idea, with products instead of sums, solves Product of Array Except Self; Subarray Sum Equals K and Contiguous Array are the other classic cases.
Sets for constant-time membership
Section titled “Sets for constant-time membership”Finally, when the question is “does exist?”, a set is all you need. Longest Consecutive Sequence shows how far that goes: put every number in a set, and start counting a streak only from an element whose predecessor is absent, so each streak is walked once and the whole algorithm is :
s = set(nums)for element in s: if element - 1 not in s: # start of a sequence count streak from elementIntersection of Two Arrays and Contains Duplicate are simpler uses of the same structure.
Choosing a technique
Section titled “Choosing a technique”The patterns differ mainly in what they cost. This table summarizes the options:
| Technique | Time | Space | When to pick |
|---|---|---|---|
| Brute force (nested loops) | never in interviews | ||
| Sort + scan | when order matters | ||
| Hash map | the default choice | ||
| Index marking | values bounded in | ||
| Prefix sum + hash | subarray sum problems |
Two kinds of mistakes account for most wrong answers in this family: off-by-one errors in array scans, and missing-element edge cases (an empty array, the missing value being or ).
Interviewers lean on different variants. As a rough guide:
| Company | Favorite variant | Difficulty |
|---|---|---|
| subarray sum with prefix + hash | Medium-Hard | |
| Meta | frequency counting + sorting | Medium |
| Amazon | Two Sum variants (sorted, BST) | Easy-Medium |
| Stripe | practical data transformation | Medium |
| Jane Street | mathematical properties of sets | Hard |
Key terms
Section titled “Key terms”- Complement lookup: a one-pass hash-map pattern that, for each element, checks whether the partner it needs (such as
target - x) has already been seen and only then records the element; it finds pairs in instead of comparing every pair in . - Frequency counting: building a map from each value to the number of times it occurs in one pass, then answering questions about duplicates, anagrams, or the most common elements from that map.
- Index marking: using an array’s own indices as a hash table when its values lie in , for example by negating the entry at index to record that was seen; it gives time with extra space.
- Prefix sum: the running total of an array up to each position, so any subarray sum is the difference of two prefix sums; with a hash map of the prefix sums seen so far, it counts the subarrays that sum to in .
In this chapter
Section titled “In this chapter”Each solution is a JavaScript function. To run one, add a small driver that calls it and prints the result and run it with Node, or paste the function into an online judge.
- Two Sum: complement lookup in its purest form. A map from value to index is checked for
target - nums[i]beforenums[i]is stored, giving the pair’s indices in one pass, or an empty array if there is none. - Contains Duplicate: a one-line answer that builds a
Setfrom the array and compares its size with the array’s length. - Missing Number: finds the one value missing from in space by letting the indices stand for the expected values. Starting from and adding
i - nums[i]at each index leaves exactly the missing number. - Product of Array Except Self: a prefix-product pass fills each slot with the product of everything to its left, and a backward pass multiplies in a running product
Rof everything to its right, all without division. For[1, 2, 3, 4]the result is[24, 12, 8, 6].