Skip to content

Lesson 5 of 40Core patterns

Arrays and Hashing

Use hash maps and sets to count, remember and group in one pass, and prefix sums to answer range questions fast.

22 min read0/7 questions

If you learn one trick for interviews, make it this one: when you are about to search a list inside a loop, put the list in a hash map instead. It turns an enormous number of O(n²) problems into O(n), and it is the first idea an interviewer hopes you will reach for. You now have the method and the cost vocabulary from Foundations; this unit fills in the pattern cheat sheet one pattern at a time, starting here.

The core move: trade memory for time

Here is the slow version of "does this list contain a duplicate?". For each number, it looks at every other number.

def has_duplicate_slow(nums):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] == nums[j]:
                return True
    return False

That is O(n²). The fast version remembers what it has seen in a set. Checking a set is O(1) on average, so one pass is enough.

Python
def has_duplicate(nums): seen = set() for x in nums: if x in seen: return True seen.add(x) return False print(has_duplicate([1, 2, 3, 1]))print(has_duplicate([1, 2, 3, 4]))
Output
Press Run (⌘ Enter) to see what happens.

You spend O(n) extra memory on the set to save a factor of n in time. That trade is almost always worth it.

ChallengeEasy

Contains Duplicate

You are given a list of integers nums. Return true if any value shows up at least twice, and false if every value is distinct.

nums = [1, 2, 3, 1]     →  true    (1 appears twice)
nums = [1, 2, 3, 4]     →  false
nums = [5, 5, 5]        →  true

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
def contains_duplicate(nums: list[int]) -> bool: # Remember what you have already seen. pass

"Seen before" with a map: two sum

Find two indices whose values add up to target. For each number x, the partner you need is target - x. Instead of scanning for it, ask a hash map: "have I already seen target - x, and where?"

Two sum on [3, 8, 4, 6], target 10

gethash(7) % 8 = 7

  1. 0empty
  2. 1empty
  3. 2empty
  4. 3empty
  5. 4empty
  6. 5empty
  7. 6empty
  8. 7empty

x = 3 needs 7. Not in the map yet.

1/5

Notice the order inside the loop: check first, then store. If you store first, a number could pair with itself (target = 6, x = 3).

Quick check
Two sum with nums = [3, 5] and target = 6. A buggy version stores x in the map before checking for target - x. What does it return?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Two Sum

Given a list of integers nums and a number target, find the two different positions whose values add up to target. Return their indices as a list in increasing order.

nums = [2, 7, 11, 15], target = 9    →  [0, 1]   (2 + 7)
nums = [3, 2, 4],      target = 6    →  [1, 2]   (2 + 4)
nums = [3, 3],         target = 6    →  [0, 1]

You may not use the same index twice.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • Exactly one valid answer exists.
def two_sum(nums: list[int], target: int) -> list[int]: # For each number, what partner would you need? pass

Frequency counting

Counting how often each thing appears is a hash map from item to count. Python gives you collections.Counter, which does it in one line. In TypeScript, use a Map with get(x) ?? 0.

Python
from collections import Counter def is_anagram(a, b): return Counter(a) == Counter(b) counts = Counter("banana")print(counts["a"], counts["n"], counts["z"])print(counts.most_common(1))print(is_anagram("listen", "silent"), is_anagram("rat", "car"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

from collections import Counter
c = Counter([2, 7, 2, 2, 7, 9])
print(c[2], c[7], c[5])
Need a nudge? Hints walk you through it.

Grouping by a key

To group things that "belong together", compute a signature that is identical for every member of a group, and use it as the map key. For anagrams, the sorted letters work: "eat", "tea" and "ate" all sort to "aet".

wordsignature (sorted)group
eataetaet: eat, tea, ate
teaaet
tanantant: tan, nat
ateaet
natant
batabtabt: bat
Python
from collections import defaultdict groups = defaultdict(list) # missing keys start as []for word in ["eat", "tea", "tan", "ate", "nat", "bat"]: groups["".join(sorted(word))].append(word)print(list(groups.values()))
Output
Press Run (⌘ Enter) to see what happens.

defaultdict(list) creates an empty list the first time you touch a key, so you never write "if key not in groups". In TypeScript, the same is const g = map.get(key) ?? []; g.push(word); map.set(key, g);.

Quick check
Sorting each word costs O(k log k) for a word of length k. Which signature is O(k) and works for lowercase English words?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Group Anagrams

Given a list of words strs, put words that are anagrams of each other (same letters, same counts) into the same group. Return the list of groups. The order of the groups, and the order inside each group, does not matter.

["eat", "tea", "tan", "ate", "nat", "bat"]
  →  [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
 
[""]   →  [[""]]
["a"]  →  [["a"]]

Constraints

  • 0 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] contains only lowercase English letters.
def group_anagrams(strs: list[str]) -> list[list[str]]: # Give every word a key that anagrams share. pass

Prefix sums

A prefix sum array stores running totals: prefix[i] is the sum of the first i numbers. Then the sum of any range nums[l..r] is one subtraction: prefix[r + 1] - prefix[l]. Build it once in O(n), answer every range question in O(1).

Prefix sums of [3, 1, 4, 1, 5]
0
0
↑i
1
2
3
4
5

prefix[0] = 0: the sum of nothing. This extra slot avoids special cases.

1/4

Prefix sums combine with a hash map for "how many subarrays sum to k?". At each position, a subarray ending here sums to k exactly when some earlier prefix equals prefix - k, so you count earlier prefixes in a map. That works even with negative numbers, where a sliding window fails.

ChallengeMedium

Count subarrays that sum to k

Return how many contiguous subarrays of nums add up to exactly k. Numbers can be negative, so a sliding window does not work here.

nums = [1, 1, 1], k = 2       →  2
nums = [1, 2, 3], k = 3       →  2   ([1, 2] and [3])
nums = [1, -1, 0], k = 0      →  3
def subarray_sum(nums: list[int], k: int) -> int: # Prefix sums + a hash map of how often each prefix sum has appeared. pass

Prefix Sums and Difference Arrays takes this much further: the counting variants, 2D prefix sums, prefix products and range updates.

The template

from collections import Counter, defaultdict
 
seen = set()                 # "have I seen x?"
index_of = {}                # value -> index, for pairs
counts = Counter(items)      # value -> how many
groups = defaultdict(list)   # signature -> members
 
for i, x in enumerate(items):
    if needed(x) in index_of:
        ...
    index_of[x] = i

Complexity: O(n) time for one pass with O(1) map operations, and O(n) space for the map. Hash map operations are O(1) on average; in theory many keys can collide into one bucket, but with built-in maps you can treat them as O(1).

How a hash map works underneath

"O(1) on average" hides a real machine, and interviewers at the senior end like to open it up. A hash map is an array of buckets. To store a key, the map calls a hash function that turns the key into a big integer, then reduces it to a bucket index, typically hash(key) % len(buckets) (or a bit mask when the size is a power of two). Lookup repeats the same calculation and checks only that bucket, so it never scans the other keys.

Two different keys can land in the same bucket. That is a collision, and there are two classic ways to handle it:

  • Separate chaining: each bucket holds a small list of (key, value) pairs. Java's HashMap does this, and turns a long chain into a small balanced tree once it passes a threshold.
  • Open addressing: every slot holds at most one entry, and on a collision the map probes other slots in a fixed sequence until it finds a free one. CPython's dict and set work this way.

Either way, the map has to compare the stored key with yours using equality, because equal hashes do not prove equal keys. That is why a key needs both a hash and an equality check that agree.

The load factor is entries divided by buckets. As it rises, buckets get crowded and lookups slow down, so the map resizes: it allocates a bigger array (usually about double) and re-inserts every key, because each key's bucket index depends on the array length. One resize costs O(n), but it happens so rarely that the cost per insert averages out to O(1). It is the same amortised argument as a dynamic array doubling, which you saw in Analyzing Code. CPython's dict resizes when it is about two thirds full.

Python
class ToyHashMap: """Separate chaining: a list of buckets, each a list of [key, value].""" def __init__(self, capacity=4, max_load=0.75): self.buckets = [[] for _ in range(capacity)] self.size = 0 self.max_load = max_load self.resizes = 0 def _bucket(self, key): return self.buckets[hash(key) % len(self.buckets)] def put(self, key, value): bucket = self._bucket(key) for pair in bucket: if pair[0] == key: # same key: overwrite pair[1] = value return bucket.append([key, value]) self.size += 1 if self.size / len(self.buckets) > self.max_load: self._resize() def get(self, key, default=None): for k, v in self._bucket(key): if k == key: return v return default def _resize(self): old = self.buckets self.buckets = [[] for _ in range(2 * len(old))] self.resizes += 1 for bucket in old: # every key moves: O(n) once for k, v in bucket: self._bucket(k).append([k, v]) m = ToyHashMap()for i in range(100): m.put(i, i * i)assert m.get(7) == 49 and m.get(1000) is Noneprint("buckets:", len(m.buckets), "resizes:", m.resizes)print("longest bucket:", max(len(b) for b in m.buckets)) class BadKey: """Every instance hashes to the same bucket.""" def __init__(self, n): self.n = n def __hash__(self): return 42 def __eq__(self, other): return self.n == other.n bad = ToyHashMap()for i in range(100): bad.put(BadKey(i), i)assert bad.get(BadKey(99)) == 99print("bad keys, longest bucket:", max(len(b) for b in bad.buckets))
Output
Press Run (⌘ Enter) to see what happens.

The second half shows the worst case. If every key hashes to the same value, every key lands in one bucket and each lookup walks a list of n items: O(n), and building the map becomes O(n²). With built-in types this does not happen by accident. It can happen on purpose: an attacker who knows your hash function can send thousands of colliding keys in a request (a hash flooding attack). That is why Python randomises string hashing per process (see PYTHONHASHSEED) and why hash("abc") changes between runs. Never persist Python's hash() values or use them across machines.

Quick check
A map doubles its bucket array whenever it gets too full. Why must it re-insert every key instead of copying the old array into the front of the new one?
Need a nudge? A hint rules out a wrong answer.

What can be a key

A key has to keep the same hash for as long as it sits in the map. If it changed, the map would look in the wrong bucket and the entry would be lost. So Python only lets you use hashable values as keys: numbers, strings, None, frozenset, and tuples whose contents are all hashable. Lists, dicts and sets are mutable, so they are not hashable.

Python
seen = {(0, 1), (2, 3)} # grid cells as tuples: fineprint((0, 1) in seen) try: {[0, 1]: "cell"}except TypeError as e: print("TypeError:", e) try: hash((1, [2])) # a tuple holding a list is not hashable eitherexcept TypeError as e: print("TypeError:", e) print(frozenset("abc") == frozenset("cab"))
Output
Press Run (⌘ Enter) to see what happens.

For your own classes, the default hash is based on identity: two different objects never match, even with the same fields. Define __eq__ and __hash__ together, or use @dataclass(frozen=True), which generates both from the fields. If you define only __eq__, Python sets __hash__ to None and the class becomes unhashable, which is deliberate: equal objects must have equal hashes.

JavaScript is the opposite trap. A Map accepts any value as a key, but objects and arrays are compared by identity (the same object in memory), not by contents. Plain objects are no better as maps, because they turn every key into a string.

JavaScript
const m = new Map();m.set([0, 1], "cell");console.log(m.get([0, 1])); // a different array: undefined const key = (r, c) => `${r},${c}`; // build a value key insteadm.set(key(0, 1), "cell");console.log(m.get(key(0, 1))); const obj = {};obj[1] = "a";obj["1"] = "b"; // same string key "1"console.log(Object.keys(obj).length);console.log(new Map([[1, "a"], ["1", "b"]]).size);
Output
Press Run (⌘ Enter) to see what happens.

For grid problems, the string key "r,c" works everywhere. When speed matters, encode a cell as one integer, r * cols + c, which hashes faster than a string or tuple. For a list of values, JSON.stringify(arr) or arr.join(",") gives a value key. Always keep a separator: without one, [1, 23] and [12, 3] both become "123".

Predict the outputJavaScript

What does this print?

const visited = new Set();
visited.add([1, 2]);
visited.add([1, 2]);
console.log(visited.size, visited.has([1, 2]));
Need a nudge? Hints walk you through it.

Majority element: Boyer-Moore voting

Find the value that appears more than n/2 times (it is guaranteed to exist). A Counter does it in O(n) time and O(n) space. The follow-up is "now in O(1) space", and the answer is the Boyer-Moore majority vote.

Think of it as a fight. Keep one candidate and a count. Each element that matches the candidate adds a vote, and each element that differs cancels one. When the count hits zero, the next element becomes the new candidate. Every cancellation removes one majority element at most together with one other element. The majority has more copies than everything else combined, so it cannot be cancelled out completely, and it is the one left standing.

Boyer-Moore on [2, 2, 1, 1, 1, 2, 2]
2
0
2
1
↑i
1
2
1
3
1
4
2
5
2
6
candidate = 2count = 2

Count is 0 at the start, so 2 becomes the candidate. The next 2 adds a vote: count = 2.

1/5
Python
def majority(nums): candidate, count = None, 0 for x in nums: if count == 0: candidate = x # nobody is ahead: back the new arrival count += 1 if x == candidate else -1 return candidate assert majority([2, 2, 1, 1, 1, 2, 2]) == 2assert majority([3, 3, 4]) == 3assert majority([7]) == 7 # Without a guaranteed majority, the candidate must be checked.nums = [1, 2, 3]c = majority(nums)print(c, nums.count(c) > len(nums) // 2)
Output
Press Run (⌘ Enter) to see what happens.

The last lines show the catch. If a majority is not guaranteed, the vote still returns someone, so you need a second pass to count the candidate. The same idea extends to "every value appearing more than n/3 times" (Majority Element II): keep two candidates and two counts, because at most two values can clear that bar, then verify both.

Index as hash: cyclic sort

Some problems say the values are in the range 1..n and ask for O(1) extra space. That is a hint that the array itself can be the hash map: value v has a natural home at index v - 1.

First Missing Positive asks for the smallest positive integer that is not in the array, in O(n) time and O(1) space. The answer must be in 1..n+1, because n numbers can fill at most the slots 1..n. So swap each value in range to its home, ignore everything else, then scan for the first index that does not hold its own value.

Find All Duplicates (values in 1..n, some appear twice) uses a different in-place mark: when you see value v, flip the sign of nums[v - 1]. If it is already negative, you have seen v before. This is the sign-marking trick that Matrix Traversal and In-Place Tricks mentions.

Python
def first_missing_positive(nums): n = len(nums) i = 0 while i < n: v = nums[i] # v belongs at index v - 1. Swap it home unless it is out of # range or a copy already sits there. if 1 <= v <= n and nums[v - 1] != v: nums[i], nums[v - 1] = nums[v - 1], v else: i += 1 for i in range(n): if nums[i] != i + 1: return i + 1 return n + 1 def find_duplicates(nums): """Values are in 1..n. Mark value v as seen by negating nums[v - 1].""" out = [] for x in nums: j = abs(x) - 1 if nums[j] < 0: out.append(abs(x)) # second visit to this slot else: nums[j] = -nums[j] return out assert first_missing_positive([3, 4, -1, 1]) == 2assert first_missing_positive([1, 2, 0]) == 3assert first_missing_positive([7, 8, 9]) == 1assert first_missing_positive([1, 1]) == 2assert find_duplicates([4, 3, 2, 7, 8, 2, 3, 1]) == [2, 3]print(first_missing_positive([3, 4, -1, 1]), find_duplicates([4, 3, 2, 7, 8, 2, 3, 1]))
Output
Press Run (⌘ Enter) to see what happens.

The while loop looks like it could be O(n²), but each swap puts one value into its final home, and a value at home is never moved again. So there are at most n swaps plus n increments: O(n). The nums[v - 1] != v check matters: without it, [1, 1] swaps a 1 with itself forever.

Both functions modify the input. In an interview, say so and ask if that is allowed. At work, mutating an array the caller still uses is a bug, and the O(n)-space set is usually the better trade.

Longest consecutive sequence

Given unsorted integers, find the length of the longest run of consecutive values ([100, 4, 200, 1, 3, 2] has 1, 2, 3, 4, length 4), in O(n). Sorting gives O(n log n), so the target says "hash set".

Put everything in a set. The naive idea, "from each x, count upward while x + 1 is in the set", is O(n²) on a long run, because every element of the run counts the rest of it again. The fix is one check: only start counting from a head, a value whose x - 1 is not in the set.

Python
def longest_consecutive(nums): values = set(nums) best = 0 for x in values: if x - 1 in values: continue # not a head: someone else counts this run length = 1 while x + length in values: length += 1 best = max(best, length) return best assert longest_consecutive([100, 4, 200, 1, 3, 2]) == 4assert longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9assert longest_consecutive([]) == 0print(longest_consecutive([100, 4, 200, 1, 3, 2]))
Output
Press Run (⌘ Enter) to see what happens.

Each run is walked exactly once, from its head, so the inner while does at most n steps in total across the whole loop. Together with the outer loop that is O(n). This "nested loop that is still linear" argument is worth saying out loud, because interviewers will ask why the inner loop does not make it quadratic. Iterate over the set, not the original list: with many duplicates of a head, the list version recounts the same run for every copy.

Quick check
In longest consecutive sequence, you remove the if x - 1 in values: continue check. On the input list(range(n)), what does the running time become?
Need a nudge? A hint rules out a wrong answer.

Common mistakes

  • Using a list for "seen". x in my_list is O(n), which quietly brings back O(n²). Use a set.
  • Storing before checking in pair problems, letting an element pair with itself.
  • Using a list as a dict key in Python. Lists are not hashable; convert to a tuple first.
  • Using plain objects as maps in JS. Keys become strings, so 1 and "1" collide. Use Map.
  • Using an Array as a key in a JS Map. Arrays compare by reference, so two equal arrays are different keys. Join them into a string.
  • Trusting the Boyer-Moore candidate when a majority is not guaranteed. Verify it with a second pass.
  • Counting runs from every element in longest consecutive sequence. Start only from heads, or it turns quadratic.
Match the pairs0/5 matched

Pick the tool for each job.

Choose an item, then its match on the other side.
Key terms
hash set
Stores unique keys with O(1) average membership checks. Python set, JS Set.
frequency map
A hash map from item to how many times it appears. Python Counter, JS Map with get(x) ?? 0.
signature
A key computed from an item so that items in the same group share it, like sorted letters for anagrams.
prefix sum
prefix[i] is the total of the first i values, so any range sum is prefix[r + 1] - prefix[l].
defaultdict
A Python dict that creates a default value (like [] or 0) the first time a missing key is used.
load factor
Entries divided by buckets. When it passes a threshold, the map allocates a bigger array and rehashes every key.
collision
Two keys mapping to the same bucket. Handled by chaining (a list per bucket) or open addressing (probe other slots).
hashable
A value whose hash never changes while it is a key, such as a number, string or tuple of hashables. Python lists are not hashable.
Boyer-Moore vote
Finds a majority element in O(1) space by letting different values cancel each other out.
cyclic sort
When values are in 1..n, swap each value to index v - 1, using the array itself as the hash table.
Interview pattern: Arrays & Hashing35 problemsSpot it: "Have I seen this before?" · duplicates · frequency · grouping