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 variantsSet and map lookups
0 of 6 solved- Contains DuplicateUp nextEasyDecode Contains Duplicate
- Two SumSprintDeep diveEasyDecode Two Sum
- Intersection of Two ArraysEasyDecode Intersection of Two Arrays
- Find the Difference of Two ArraysEssentialsDeep diveEasyDecode Find the Difference of Two Arrays
- Longest Consecutive SequenceSprintDeep diveMediumDecode Longest Consecutive Sequence
- Insert Delete GetRandom O(1)SprintDeep diveMediumDecode Insert Delete GetRandom O(1)
Frequency counting
0 of 8 solved- Valid AnagramSprintDeep diveEasyDecode Valid Anagram
- Majority ElementSprintDeep diveEasyDecode Majority Element
- Ransom NoteSprintDeep diveEasyDecode Ransom Note
- First Unique Character in a StringEasyDecode First Unique Character in a String
- Unique Number of OccurrencesEssentialsDeep diveEasyDecode Unique Number of Occurrences
- Top K Frequent ElementsMediumDecode Top K Frequent Elements
- Determine if Two Strings Are CloseEssentialsDeep diveMediumDecode Determine if Two Strings Are Close
- H-IndexSprintDeep diveMediumDecode H-Index
Keys and encodings
0 of 6 solved- Isomorphic StringsSprintDeep diveEasyDecode Isomorphic Strings
- Word PatternSprintDeep diveEasyDecode Word Pattern
- Group AnagramsSprintDeep diveMediumDecode Group Anagrams
- Encode and Decode StringsMediumDecode Encode and Decode Strings
- Valid SudokuSprintDeep diveMediumDecode Valid Sudoku
- Equal Row and Column PairsEssentialsDeep diveMediumDecode Equal Row and Column Pairs
Prefix sums
0 of 7 solved- Range Sum Query (Immutable)EasyDecode Range Sum Query (Immutable)
- Find Pivot IndexEssentialsDeep diveEasyDecode Find Pivot Index
- Find the Highest AltitudeEssentialsDeep diveEasyDecode Find the Highest Altitude
- Product of Array Except SelfEssentialsSprintDeep diveMediumDecode Product of Array Except Self
- Subarray Sum Equals KMediumDecode Subarray Sum Equals K
- Contiguous ArrayMediumDecode Contiguous Array
- Continuous Subarray SumMediumDecode Continuous Subarray Sum
Index tricks
0 of 5 solved- Find All Numbers Disappeared in an ArrayEasyDecode Find All Numbers Disappeared in an Array
- Longest Common PrefixSprintDeep diveEasyDecode Longest Common Prefix
- Sort ColorsMediumDecode Sort Colors
- Rotate ArraySprintDeep diveMediumDecode Rotate Array
- Zigzag ConversionSprintDeep diveMediumDecode Zigzag Conversion
Matrix traversal
0 of 3 solved- Spiral MatrixSprintDeep diveMediumDecode Spiral Matrix
- Set Matrix ZeroesSprintDeep diveMediumDecode Set Matrix Zeroes
- Rotate ImageSprintDeep diveMediumDecode Rotate Image
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.
Start with an empty map. For each number we will ask: is target - x already here?
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).
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 prompt | What 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 negatives | Prefix sums plus a hash map |
| "range sum", "many queries" on a fixed array | A 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
| Constraint | What it implies |
|---|---|
n <= 10^4 to 10^5 | O(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^9 | Values are too spread out for an array indexed by value. Use a hash map. |
| Only lowercase English letters | At most 26 keys. Counts fit in a fixed array and count as O(1) space. |
1 <= nums[i] <= n | Every 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
| Shape | Usual tool |
|---|---|
| Unsorted array, return indices | Hash map from value to index (sorting would lose positions) |
| Strings in, true/false out | Counting, or a mapping check |
| List of strings in, list of lists out | Grouping by a key |
| Return a count of subarrays | Prefix sums with a map of counts |
| Return the longest subarray | Prefix 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 place | Index 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 each prompt fragment to the tool it points at.
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.
Put every value in a set so "is x here?" is O(1).
Press Run (⌘ Enter) to see what happens.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".
Count the letters of s = "abc": one of each.
Press Run (⌘ Enter) to see what happens.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.
What does this print?
counts = {}
for ch in "mississippi":
counts[ch] = counts.get(ch, 0) + 1
print(counts["s"], counts["p"], len(counts))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.
eat sorted is aet. New key, new group.
Press Run (⌘ Enter) to see what happens.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".
Seed the map with total 0 seen once: that represents the empty prefix, so subarrays starting at index 0 can be counted.
Press Run (⌘ Enter) to see what happens.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.
{0: 1} instead of empty?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.
Values are in 1..8, so each value v names index v - 1. We will mark index v - 1 by making it negative.
Press Run (⌘ Enter) to see what happens.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.
Walk the top row left to right, then move top down.
Press Run (⌘ Enter) to see what happens.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 the questions in the order you should ask them when an array problem lands.
- Tap the steps below in the right order.
Which sub-pattern fits each problem?
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 <= bottomandleft <= 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.
nums = [1, -1, 1, -1], find the number of subarrays summing to 0. Why does a sliding window fail here?How to talk it through
- hash map
- A key to value store with O(1) average lookup, insert and delete.
dictin Python,Mapin TypeScript. - frequency map
- A hash map from each item to how many times it appears. Python's
Counterbuilds 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.