Skip to content

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.

16 min read0/5 questions

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

PatternCore moveTypical clue
Arrays and hashingCount or look up in O(1)"seen before", "frequency", "group by", "unsorted"
Two pointersMove two indices toward or along each other"sorted", "pair", "in place", "palindrome"
Sliding windowGrow and shrink a contiguous range"substring", "subarray", "longest/shortest", "at most k"
Prefix sumsPrecompute running totals, subtract to get any range"sum of subarray equals", "range sum", negatives allowed
Binary searchHalve a sorted range or a monotone answer"sorted", "minimum x such that", O(log n) required
StackRemember 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

PromptDeciding cluePattern
"Find two numbers that add up to target. Return their indices."Nothing says sorted, and indices must be keptHash map, one pass
"The array is sorted in non-decreasing order. Find two numbers that add up to target."sortedTwo 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

PromptDeciding cluePattern
"Longest substring without repeating characters."substring = contiguousSliding window
"Longest subsequence that is increasing."subsequence = may skipDynamic programming (or binary search with patience sorting)
"Pick any k numbers with the largest sum."any = not contiguousSort 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.

Match the pairs0/4 matched

Which pattern does the deciding word point to?

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

Contrast 3: positive values or negatives allowed

PromptDeciding cluePattern
"Shortest subarray with sum ≥ target. All values are positive."positiveSliding 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.

Prefix sums: count subarrays with sum k = 3
1
0
2
1
-1
2
2
3
prefix = 0seen = {0: 1}count = 0

Start with prefix 0 seen once. That stands for the empty prefix before index 0.

1/5
Predict the outputPython

What does this print?

nums = [2, -1, 3]
prefix = [0]
for x in nums:
  prefix.append(prefix[-1] + x)
print(prefix[3] - prefix[1])
Need a nudge? Hints walk you through it.

Contrast 4: searching a value or searching an answer

PromptDeciding cluePattern
"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 passesBinary search on the answer
"Find the number of hours at a given speed."one value, no searchA 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"

PromptDeciding cluePattern
"Is every bracket closed in the right order?"matching, nestingStack of open brackets
"For each day, how many days until a warmer one?"next greaterMonotonic stack
"Max temperature in each window of 3 days."window plus maxMonotonic deque (sliding window)
"Is the string a palindrome?"compare endsTwo 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 the pairs0/5 matched

Match each prompt to its pattern.

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

Constraint tells

When the wording is ambiguous, the constraints usually decide.

ConstraintWhat it suggests
n <= 10^5 or 10^6O(n) or O(n log n). Nested loops are out.
n <= 10^3O(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 rangeBinary search on the answer.
"sorted" anywhereBinary search or two pointers. Using a hash map wastes the hint.
Values can be negative, question is about sumsPrefix sums, not a window.
Quick check
'Return true if any two values in the array sum to target. Use O(1) extra space.' n is up to 10^5. Which approach fits?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/6 matched

Final mix: name the pattern from the deciding clue.

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

A decode routine for this category

When an array or string question lands, ask these in order. The first yes usually wins.

  1. Is the input sorted, or can I sort it without losing what I must return? → two pointers or binary search.
  2. Is the answer a contiguous range with a rule? Are values non-negative? → sliding window. Negatives and sums → prefix sums.
  3. Is the slow part a lookup or a count? → hash map or set.
  4. Does each element wait for a later element to resolve it, newest first? → stack.
  5. 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.

ChallengeMedium

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.
def two_sum_sorted(numbers: list[int], target: int) -> list[int]: # The list is sorted. Start at both ends. pass
ChallengeMedium

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   →  23

A pile of p bananas takes ceil(p / k) hours.

Constraints

  • 1 <= piles.length <= 10^4
  • piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
def min_eating_speed(piles: list[int], h: int) -> int: # Binary search on the answer: the speed k. pass
Key terms
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.