Skip to content

Arrays & Hashing

Reach for it when the problem says

  • "Have I seen this before?"
  • duplicates
  • frequency
  • grouping
Solved
0/35Solved
Problems
35Problems
Variants
6Variants

Problems

6 variants

Set and map lookups

0 of 6 solved

Frequency counting

0 of 8 solved

Keys and encodings

0 of 6 solved

Prefix sums

0 of 7 solved

Index tricks

0 of 5 solved

Matrix traversal

0 of 3 solved

Pattern guide

Arrays and hashing is the first pattern interviewers test, and it hides inside most of the others. Two Sum, Group Anagrams and Subarray Sum Equals K all come down to the same move: instead of searching the array again and again, you remember what you have already seen in a structure that answers in O(1).

What it is

Most brute-force array solutions have a nested loop. The outer loop picks an element, and the inner loop searches the rest of the array for something related to it: a partner, a duplicate, an earlier total. That inner search is what makes them O(n²).

A hash map (Python dict, TypeScript Map) or hash set (set, Set) replaces the inner search with a lookup that takes O(1) on average. You walk the array once, and at each step you ask the map a question about the past, then record the current element for the future.

Watch it on Two Sum with nums = [2, 7, 11, 15] and target = 18. The map stores value → index.

Two Sum: ask, then remember
  1. 0empty
  2. 1empty
  3. 2empty
  4. 3empty
  5. 4empty
  6. 5empty

Start with an empty map. For each number we will ask: is target - x already here?

1/4

The order inside each step matters: look up first, then insert. If you insert first, a number can pair with itself (think [3, 3] with target 6 versus [3] with target 6).

Quick check
Why is the hash map version of Two Sum O(n) while the nested loop is O(n²)?
Need a nudge? A hint rules out a wrong answer.

The trade you are making

Hashing is a space for time trade. You spend O(n) extra memory on the map so that each question costs O(1) instead of O(n). In an interview, say that trade out loud, because the natural follow-up is "can you do it with less memory?" Sometimes the answer is yes: Majority Element has a two-variable voting trick, and Find All Numbers Disappeared can mark the input array itself. Those follow-ups are why this guide includes index tricks alongside the maps.

The other classic alternative is sorting. Sorting first costs O(n log n) and often makes the rest easy (duplicates become neighbours, pairs can be found with two pointers). Prefer the map when you must keep original positions, when the prompt demands O(n), or when you only need membership and counts. Prefer sorting when memory is tight or when the output must be sorted anyway.

Under the hood: why lookups are only O(1) on average

A hash map turns a key into a number with a hash function, then uses that number to pick a bucket in an internal array. Looking a key up means hashing it and checking one bucket, which is constant work as long as buckets stay short. When the map gets full, it grows (typically doubling) and re-places every key. That resize is O(n), but it happens rarely enough that inserts are O(1) amortized.

The "average" matters: if many keys landed in the same bucket (a collision storm), lookups would degrade toward O(n). Python and JavaScript engines use good hash functions and randomisation for strings, so in interviews you can treat lookups as O(1) and mention the worst case if asked.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"contains a duplicate", "appears twice", "seen before"A hash set of seen values
"two numbers that add up to", "complement", "pair" (unsorted, return indices)Hash map from value to index
"anagram", "same letters", "frequency", "most common", "at least k times"Counting with a hash map or a 26-slot array
"group", "bucket", "categorise"Map from a canonical key to a list
"one-to-one", "pattern", "isomorphic", "bijection"Two maps, one per direction
"contiguous subarray", "sum equals k", "balanced", "multiple of k" with negativesPrefix sums plus a hash map
"range sum", "many queries" on a fixed arrayA prefix sum array
"in place", "O(1) extra space", "values in the range 1 to n"Index tricks: use the array as its own table
"matrix", "rotate", "spiral", "row and column"Matrix traversal with careful index bookkeeping

Constraint clues

ConstraintWhat it implies
n <= 10^4 to 10^5O(n²) is 10^8 to 10^10 steps. You need O(n) or O(n log n), and a hash map usually gives O(n).
-10^9 <= nums[i] <= 10^9Values are too spread out for an array indexed by value. Use a hash map.
Only lowercase English lettersAt most 26 keys. Counts fit in a fixed array and count as O(1) space.
1 <= nums[i] <= nEvery value is also a valid index (after subtracting 1). Index tricks are on the table.
"Must run in O(n)" or "better than O(n log n)"Sorting is ruled out on purpose. Hashing or bucket sort is expected.
Small fixed size (a 9 by 9 board, up to 20 items)Speed is not the challenge. Clean bookkeeping is.

Input and output shape clues

ShapeUsual tool
Unsorted array, return indicesHash map from value to index (sorting would lose positions)
Strings in, true/false outCounting, or a mapping check
List of strings in, list of lists outGrouping by a key
Return a count of subarraysPrefix sums with a map of counts
Return the longest subarrayPrefix sums with a map of first indices
A class with operations that must be O(1)Hash map plus an array, combined
Function returns nothing, list or matrix changed in placeIndex tricks or matrix traversal with swaps

Looks like it but isn't

  • Sorted input with a pair target is Two Pointers, not hashing. Two Sum II gives you a sorted array precisely so you can do it in O(1) space.
  • "Longest substring with at most k distinct" uses a hash map, but the real pattern is Sliding Window: the answer is a contiguous range that grows and shrinks.
  • Subarray sums with only positive numbers can be a sliding window. Once negatives appear, the window logic breaks and you need prefix sums with a map.
  • "Top k" with a demand for sorted output often wants a Heap. Plain "any order" top k can use bucket sort.
  • Grid problems where things spread to neighbours (islands, rotting oranges) are Graphs. Matrix traversal here never explores; it visits cells in a fixed order.
Match the pairs0/5 matched

Match each prompt fragment to the tool it points at.

Choose an item, then its match on the other side.

The sub-patterns

Set and map lookups

When it applies: at each element you need to know whether something related was seen before: the value itself (duplicates), its complement (pairs), or its neighbour (consecutive runs). Also for designing structures that need O(1) membership.

Longest Consecutive Sequence: only start at run starts
100
0
4
1
200
2
1
3
3
4
2
5
set = {100, 4, 200, 1, 3, 2}best = 0

Put every value in a set so "is x here?" is O(1).

1/4
Python
def has_pair(nums: list[int], target: int) -> list[int]: index_of: dict[int, int] = {} for i, x in enumerate(nums): need = target - x if need in index_of: # ask about the past return [index_of[need], i] index_of[x] = i # remember for the future return [] print(has_pair([2, 7, 11, 15], 18))print(has_pair([3, 3], 6))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(n) space. Best-known problems: Two Sum, Contains Duplicate, Longest Consecutive Sequence, Insert Delete GetRandom O(1).

Frequency counting

When it applies: the answer depends on how many times things appear, not where. Anagrams, ransom notes, majority, "first unique", "top k frequent".

Valid Anagram: count up, then count down
  1. 0empty
  2. 1empty
  3. 2"a":1
  4. 3"b":1
  5. 4"c":1

Count the letters of s = "abc": one of each.

1/4
Python
def counts_of(items) -> dict: counts: dict = {} for x in items: counts[x] = counts.get(x, 0) + 1 return counts print(counts_of("banana"))print(counts_of([3, 1, 3, 3, 2]))# Two strings are anagrams exactly when their counts match.print(counts_of("listen") == counts_of("silent"))
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time. Space is O(k) for k distinct keys, which is O(1) when the alphabet is fixed (26 letters). Python's collections.Counter does the same job in one line. Best-known problems: Valid Anagram, Top K Frequent Elements, Majority Element, Ransom Note, Determine if Two Strings Are Close.

Predict the outputPython

What does this print?

counts = {}
for ch in "mississippi":
  counts[ch] = counts.get(ch, 0) + 1
print(counts["s"], counts["p"], len(counts))
Need a nudge? Hints walk you through it.

Keys and encodings

When it applies: things that should be treated as equal look different (anagrams, rows of a matrix, cells in the same Sudoku box), or two sequences must correspond one-to-one. You design a key that makes equal things collide, or an encoding that can be undone.

Group Anagrams: the sorted word is the key

puthash("aet") % 5 = 4

  1. 0empty
  2. 1empty
  3. 2empty
  4. 3empty
  5. 4"aet":"eat"

eat sorted is aet. New key, new group.

1/4
Python
def group_by_key(words: list[str]) -> list[list[str]]: groups: dict[str, list[str]] = {} for w in words: key = "".join(sorted(w)) # equal for all anagrams groups.setdefault(key, []).append(w) return list(groups.values()) print(group_by_key(["eat", "tea", "tan", "ate", "nat", "bat"]))# Composite keys name a Sudoku box: (row // 3, col // 3)print((4 // 3, 7 // 3))
Output
Press Run (⌘ Enter) to see what happens.

In TypeScript, arrays are compared by reference, so new Map<number[], …> will not group equal arrays. Join them into a string with a separator (row.join(",")) to get a key that compares by value. For one-to-one problems like Isomorphic Strings and Word Pattern, keep two maps, one per direction.

Complexity: O(n · k) where k is the cost of building one key. Best-known problems: Group Anagrams, Valid Sudoku, Isomorphic Strings, Encode and Decode Strings.

Prefix sums

When it applies: the question is about sums (or products) over contiguous ranges. prefix[j] - prefix[i] is the sum of the elements between them, so a range question becomes a question about two running totals. Pair it with a hash map when you need "some earlier total equal to X".

Subarray Sum Equals K, k = 3
1
0
2
1
1
2
2
3
1
4
total = 0seen = {0: 1}count = 0

Seed the map with total 0 seen once: that represents the empty prefix, so subarrays starting at index 0 can be counted.

1/5
Python
def count_subarrays(nums: list[int], k: int) -> int: seen = {0: 1} # running total -> how many times total = count = 0 for x in nums: total += x count += seen.get(total - k, 0) # earlier totals that close a range seen[total] = seen.get(total, 0) + 1 return count print(count_subarrays([1, 2, 1, 2, 1], 3))print(count_subarrays([1, -1, 0], 0))
Output
Press Run (⌘ Enter) to see what happens.

Three variations cover most problems. To count subarrays, map each total to how many times it appeared. To find the longest subarray, map each total to the first index it appeared and never overwrite it (Contiguous Array). For divisibility, store total % k instead of the total (Continuous Subarray Sum). And when there are many range queries on a fixed array, just store the prefix array itself (Range Sum Query).

Complexity: O(n) time, O(n) space. Best-known problems: Product of Array Except Self, Subarray Sum Equals K, Contiguous Array, Find Pivot Index.

Quick check
In Subarray Sum Equals K, why does the map start as {0: 1} instead of empty?
Need a nudge? A hint rules out a wrong answer.

Index tricks

When it applies: the prompt wants in place or O(1) extra space, and the values or the structure give you room to work inside the array: values in 1..n that double as indices, a tiny set of values (0, 1, 2), or a transformation that is a combination of reversals.

Find All Numbers Disappeared: mark by flipping signs
4
0
3
1
2
2
7
3
8
4
2
5
3
6
1
7

Values are in 1..8, so each value v names index v - 1. We will mark index v - 1 by making it negative.

1/3
Python
def rotate_right(nums: list[int], k: int) -> None: n = len(nums) k %= n def reverse(lo: int, hi: int) -> None: while lo < hi: nums[lo], nums[hi] = nums[hi], nums[lo] lo += 1 hi -= 1 reverse(0, n - 1) # whole list reverse(0, k - 1) # first k reverse(k, n - 1) # the rest data = [1, 2, 3, 4, 5, 6, 7]rotate_right(data, 3)print(data)
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) extra space. Best-known problems: Find All Numbers Disappeared in an Array, Sort Colors, Rotate Array, Longest Common Prefix.

Matrix traversal

When it applies: the input is a 2D grid and the task is a fixed visiting order or a geometric transform: spiral reads, rotations, transposes, or row and column effects. There is no search; the hard part is boundaries.

Spiral Matrix: shrink four walls
123
456
789

Walk the top row left to right, then move top down.

1/5
Python
def rotate_clockwise(matrix: list[list[int]]) -> None: n = len(matrix) for r in range(n): # transpose: only above the diagonal for c in range(r + 1, n): matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] for row in matrix: # then mirror each row row.reverse() m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]rotate_clockwise(m)print(m)
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(m · n) time, usually O(1) extra space. Best-known problems: Spiral Matrix, Rotate Image, Set Matrix Zeroes.

Decision checklist

Put it in order5 steps

Put the questions in the order you should ask them when an array problem lands.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Which sub-pattern fits each problem?

Choose an item, then its match on the other side.

Traps

  • Inserting before looking up. In Two Sum and prefix-sum problems, check the map for the partner before you store the current element, or an element pairs with itself or a range has length zero.
  • Forgetting the seed. Prefix-sum maps start with {0: 1} (counting) or {0: -1} (lengths). Without it you miss every answer that starts at index 0.
  • Overwriting first indices. For "longest" questions, only store a total the first time you see it. Updating it later shortens every answer.
  • A set where you needed counts. "aab" and "abb" have the same set of letters. Anagram and ransom checks need counts.
  • One map for a two-way mapping. "badc" and "baba" pass a single s → t map. One-to-one needs both directions.
  • Mutable keys. Python lists cannot be dict keys (use a tuple), and TypeScript compares arrays by reference (join them into a string with a separator).
  • Sliding window with negatives. If numbers can be negative, a window cannot know when to shrink. Switch to prefix sums.
  • Writing results while scanning a matrix. In Set Matrix Zeroes, zeros you write look like original zeros. Record first, write second.
  • Missing the guards in spiral order. After walking the top row and right column, re-check top <= bottom and left <= right.
  • k larger than n. Rotations should start with k %= n.

Edge cases to always test: an empty list (if allowed), one element, all equal values, duplicates, negatives and zero, and the longest or largest answer sitting at the very start or very end.

Quick check
nums = [1, -1, 1, -1], find the number of subarrays summing to 0. Why does a sliding window fail here?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
hash map
A key to value store with O(1) average lookup, insert and delete. dict in Python, Map in TypeScript.
frequency map
A hash map from each item to how many times it appears. Python's Counter builds one.
canonical key
A form that makes things you consider equal produce the same key, like a sorted word for anagrams.
prefix sum
The running total up to each index. The sum of a range is the difference of two prefix sums.
index marking
Using the array as its own lookup table, for example by flipping the sign at index v - 1.
bijection
A one-to-one mapping in both directions. Check it with two maps.