Lesson 20 of 27Decode by category
Decoding Arrays and Strings
Tell hashing, two pointers, sliding window, prefix sums, binary search, and stack problems apart from one deciding clue.
Most interview questions on arrays and strings look alike at first glance: a list of numbers, a string, a target. Yet they split across six different patterns, and picking the wrong one costs you twenty minutes. The good news is that each pattern has a deciding clue, usually one word in the prompt or one line in the constraints.
This lesson trains that eye by putting near-identical prompts side by side and pointing at the word that decides. It does not re-teach the patterns. If one of them feels shaky, go back to its lesson in the Algorithms & Patterns course: Arrays and Hashing, Two Pointers, Sliding Window, Prefix Sums and Difference Arrays, Binary Search, or Stack.
The six candidates
| Pattern | Core move | Typical clue |
|---|---|---|
| Arrays and hashing | Count or look up in O(1) | "seen before", "frequency", "group by", "unsorted" |
| Two pointers | Move two indices toward or along each other | "sorted", "pair", "in place", "palindrome" |
| Sliding window | Grow and shrink a contiguous range | "substring", "subarray", "longest/shortest", "at most k" |
| Prefix sums | Precompute running totals, subtract to get any range | "sum of subarray equals", "range sum", negatives allowed |
| Binary search | Halve a sorted range or a monotone answer | "sorted", "minimum x such that", O(log n) required |
| Stack | Remember unresolved items, newest first | "matching", "nested", "next greater", "previous smaller" |
Prefix sums live under Arrays and hashing in Practice, because they almost always pair with a hash map.
Contrast 1: sorted or not
| Prompt | Deciding clue | Pattern |
|---|---|---|
"Find two numbers that add up to target. Return their indices." | Nothing says sorted, and indices must be kept | Hash map, one pass |
"The array is sorted in non-decreasing order. Find two numbers that add up to target." | sorted | Two pointers from both ends |
With sorted input, the sum of the two ends tells you which pointer to move: too small, move left up; too big, move right down. That needs no extra memory, so if the follow-up is "O(1) extra space", the sorted version is the one. Without sorting, the only O(n) way to find a complement is to look it up.
Contrast 2: contiguous or not
| Prompt | Deciding clue | Pattern |
|---|---|---|
| "Longest substring without repeating characters." | substring = contiguous | Sliding window |
| "Longest subsequence that is increasing." | subsequence = may skip | Dynamic programming (or binary search with patience sorting) |
| "Pick any k numbers with the largest sum." | any = not contiguous | Sort or heap |
"Substring" and "subarray" mean the elements sit next to each other. "Subsequence" and "subset" mean you may skip. A window only works on contiguous ranges.
Which pattern does the deciding word point to?
Contrast 3: positive values or negatives allowed
| Prompt | Deciding clue | Pattern |
|---|---|---|
| "Shortest subarray with sum ≥ target. All values are positive." | positive | Sliding window, shrink while valid |
| "Count subarrays whose sum equals k. Values may be negative." | negative, and "count" | Prefix sums plus a hash map |
A window relies on a promise: growing the window increases the sum, shrinking decreases it. Negatives break the promise, because adding an element can make the sum smaller. Prefix sums do not care. The sum of nums[i..j] is prefix[j + 1] - prefix[i], so "is there an earlier prefix equal to current - k?" is a hash map lookup.
Start with prefix 0 seen once. That stands for the empty prefix before index 0.
What does this print?
nums = [2, -1, 3] prefix = [0] for x in nums: prefix.append(prefix[-1] + x) print(prefix[3] - prefix[1])
Contrast 4: searching a value or searching an answer
| Prompt | Deciding clue | Pattern |
|---|---|---|
"Return the index of target in a sorted array in O(log n)." | sorted, O(log n) | Classic binary search |
| "Find the minimum eating speed so all piles are finished within h hours." | minimum x such that a check passes | Binary search on the answer |
| "Find the number of hours at a given speed." | one value, no search | A loop |
The second one is the sneaky one. Nothing in it is sorted. But the answer has a monotone property: if speed 6 works, every speed above 6 works too. Whenever you can write can_finish(speed) and it flips from false to true exactly once, you can binary search the speed. Constraints like "piles up to 10^9" are a tell: you cannot try every speed, but you can try log₂(10^9), about 30 of them.
Contrast 5: matching, nesting, and "next greater"
| Prompt | Deciding clue | Pattern |
|---|---|---|
| "Is every bracket closed in the right order?" | matching, nesting | Stack of open brackets |
| "For each day, how many days until a warmer one?" | next greater | Monotonic stack |
| "Max temperature in each window of 3 days." | window plus max | Monotonic deque (sliding window) |
| "Is the string a palindrome?" | compare ends | Two pointers |
A stack fits when the most recent unresolved item is the one that gets resolved next. A closing bracket matches the newest open one. A warm day resolves the coldest recent days still waiting.
Match each prompt to its pattern.
Constraint tells
When the wording is ambiguous, the constraints usually decide.
| Constraint | What it suggests |
|---|---|
n <= 10^5 or 10^6 | O(n) or O(n log n). Nested loops are out. |
n <= 10^3 | O(n²) is fine. A pair check may be the intended answer. |
| "O(1) extra space" or "in place" | Two pointers, or overwrite the input. No hash map. |
| "lowercase English letters" | A 26-slot count array instead of a hash map. |
Values up to 10^9, answer is a number in a range | Binary search on the answer. |
| "sorted" anywhere | Binary search or two pointers. Using a hash map wastes the hint. |
| Values can be negative, question is about sums | Prefix sums, not a window. |
Final mix: name the pattern from the deciding clue.
A decode routine for this category
When an array or string question lands, ask these in order. The first yes usually wins.
- Is the input sorted, or can I sort it without losing what I must return? → two pointers or binary search.
- Is the answer a contiguous range with a rule? Are values non-negative? → sliding window. Negatives and sums → prefix sums.
- Is the slow part a lookup or a count? → hash map or set.
- Does each element wait for a later element to resolve it, newest first? → stack.
- Is the answer a number where "x works" implies "bigger x works"? → binary search on the answer.
The Decoder has a decoy stage for exactly this: for each problem, it lists the patterns people wrongly reach for. Try naming the decoys yourself before revealing them.
Two Sum II (Sorted Input)
You are given a list numbers that is sorted in ascending order and a number target. Find the two different positions whose values add up to target and return their 0-based indices in increasing order.
numbers = [2, 7, 11, 15], target = 9 → [0, 1]
numbers = [2, 3, 4], target = 6 → [0, 2]
numbers = [-1, 0], target = -1 → [0, 1]Constraints
2 <= numbers.length <= 3 * 10^4-1000 <= numbers[i] <= 1000-1000 <= target <= 1000- Exactly one valid pair exists.
- Use only O(1) extra space.
Koko Eating Bananas
There are piles of bananas, piles[i] in pile i, and h hours until the guards return. Each hour Koko picks one pile and eats up to k bananas from it. If the pile has fewer than k left, she finishes it and waits out the rest of that hour. Return the smallest whole-number speed k that lets her eat every banana within h hours.
piles = [3, 6, 7, 11], h = 8 → 4
piles = [30, 11, 23, 4, 20], h = 5 → 30
piles = [30, 11, 23, 4, 20], h = 6 → 23A pile of p bananas takes ceil(p / k) hours.
Constraints
1 <= piles.length <= 10^4piles.length <= h <= 10^91 <= piles[i] <= 10^9
- deciding clue
- The word or constraint that separates two patterns that otherwise fit, such as 'sorted' or 'negative'.
- contiguous
- Elements next to each other: substrings and subarrays. Subsequences and subsets may skip.
- prefix sum
- A running total where any range sum is
prefix[j + 1] - prefix[i]. - binary search on the answer
- Halving the range of possible answers when 'x works' implies every larger x also works.
- monotone
- Only ever moves one way, such as a check that flips from false to true exactly once.