Skip to content
TOPIC · 12 PROBLEMS · 6 PATTERNS

Arrays and hashing

Most brute-force answers compare every item with every other item. A hash map remembers what you have already seen, so one pass is enough.

How to spot a hashing problem

“duplicate”Has this value appeared before? A set answers that in constant time, so you never look back over the array.
“add up to”A pair with a target sum. For each number you already know the partner you need, so ask the map if it has turned up yet.
“anagram”Same letters, different order. Count each letter, or sort the word, and compare the results instead of the words.
“most frequent”Anything about how often something happens. Build a count first, then answer the question from the counts.

Six patterns cover almost everything

Seen-set

O(n)

Keep a set of everything so far. Each new item is one lookup: in the set, or not.

Reach for it when you need to know whether a value has turned up before, or whether one exists at all.Go deeper: How a hash map finds a key

Prefix sums

O(n)

Keep a running total. The sum of any slice is the difference between two totals, so a map of totals seen finds slices with a given sum.

Reach for it when the question is about contiguous slices and their sums or products.Go deeper: Prefix sums: any range total in one subtraction

Index as key

O(n), O(1) space

When values are known to lie between 1 and n, the array itself can be the hash table. Mark value v at index v − 1.

Reach for it when values fit the array’s own index range and you are asked for constant extra space.Go deeper: Why reading an array by index is instant

The one template to memorise

Only one to learn by heart: the complement lookup from Two Sum. Look up what you need before you store what you have. Most of the others are a count or a set built the same way.

solution.py
def two_sum(nums, target):
seen = {} # value -> index
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Contains DuplicateSeen-setEasyRead
2Valid AnagramFrequency countEasyRead
3Two SumComplement mapEasyRead
4Majority ElementFrequency countEasyRead
5Group AnagramsGroup by keyMediumRead
6Top K Frequent ElementsFrequency countMediumRead
7Product of Array Except SelfPrefix sumsMediumRead
8Valid SudokuSeen-setMediumRead
9Longest Consecutive SequenceSeen-setMediumRead
10Subarray Sum Equals KPrefix sumsMediumRead
11Find All Duplicates in an ArrayIndex as keyMediumRead
12First Missing PositiveIndex as keyHardRead
Next upTwo pointersSliding window