Phase 3: Linear Management & Searching
In Phases 1 and 2 you learned to store data in lists, strings, dictionaries, stacks and queues. This phase is about managing that data efficiently: putting it in order, finding things in it fast, and answering questions about ranges of it without re-scanning everything. By the end you will be able to sort with custom rules, write a binary search that does not go wrong at the edges, and recognise the four patterns that solve most "array" interview problems: two pointers, sliding window, prefix sums and Kadane's algorithm. You will also handle intervals and walk a matrix with confidence.
Every technique here has the same goal: turn a solution that looks at every pair of elements (O(n²)) into one that looks at each element once or twice (O(n) or O(n log n)). So we start with what those symbols mean.
Big-O: why O(n log n) beats O(n²)
Big-O notation describes how the running time of an algorithm grows with the size of its input, ignoring constant factors. The ones you need this phase:
| Big-O | Name | Typical shape |
|---|---|---|
| O(1) | constant | a dict lookup, nums[i], one arithmetic step |
| O(log n) | logarithmic | halving the search space each step (binary search) |
| O(n) | linear | one pass over the data |
| O(n log n) | linearithmic | sorting; a loop with a binary search inside |
| O(n²) | quadratic | a loop inside a loop over the same data |
The gap between the last two is enormous. For n = 10,000, n² is 100,000,000 while n log n is about 130,000: roughly 750 times less work. For n = 1,000,000 the ratio is around 50,000. That is why "aim for O(n log n)" or "aim for O(n)" appears in problem constraints: a nested loop that is fine for 100 elements will time out on 100,000.
Press Run on this to see the four curves side by side. Both axes are logarithmic, so every grid line is ten times the one before, and each power of n becomes a straight line whose steepness is the power: n^2 climbs twice as steeply as n.
import math
ns = [2 ** k for k in range(1, 21)]
plot(ns, [math.log2(n) for n in ns], label="log n", logx=True, logy=True, xlabel="n", ylabel="steps")
plot(ns, ns, label="n")
plot(ns, [n * math.log2(n) for n in ns], label="n log n")
plot(ns, [n * n for n in ns], label="n²")
A quick way to estimate: a nested loop over the same list is O(n²); a single loop is O(n); anything that repeatedly halves its range is O(log n); sorting is O(n log n). If you sort once and then do a single pass, the whole thing is O(n log n) because the sort dominates.
import time
def count_pairs_slow(nums, target):
count = 0
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
count += 1
return count
def count_pairs_fast(nums, target):
seen = {}
count = 0
for x in nums:
count += seen.get(target - x, 0)
seen[x] = seen.get(x, 0) + 1
return count
nums = list(range(3000))
for f in (count_pairs_slow, count_pairs_fast):
t = time.perf_counter()
f(nums, 3000)
print(f.__name__, "took about", round((time.perf_counter() - t) * 1000), "ms")
On a typical laptop the output looks like:
count_pairs_slow took about 100 ms
count_pairs_fast took about 1 ms
Same answer, about a hundred times faster, and the gap only widens as n grows.
Upper, lower and tight bounds
Big-O is only one of three statements you can make about how a cost grows, and the other two matter as soon as somebody claims an algorithm cannot be made faster.
- f \in \mathcal{O}(g) — f grows no faster than g: an upper bound, the promise a library makes.
- f \in \Omega(g) — f grows at least as fast as g: a lower bound, the excuse a slow program offers.
- f \in \Theta(g) — both at once, so f and g grow at the same rate.
Saying "sorting by comparisons is \Omega(n\log n)" says no comparison sort can do better; saying merge sort is \Theta(n\log n) says it hits that bound exactly. Only \Theta is a real answer to "how fast is it?".
The quickest way to decide which applies is the limit of the ratio. If f(n)/g(n) \to 0 then f is in \mathcal{O}(g) and not \Theta(g); if it tends to a positive constant they are \Theta of each other; if it runs away to infinity then f is in \Omega(g) and not \Theta(g). You can watch that happen:
import math
def ratio(f, g, ns):
return [round(f(n) / g(n), 3) for n in ns]
ns = [10, 100, 1000, 10000, 100000]
print("n log n / n^2 ", ratio(lambda n: n * math.log2(n), lambda n: n * n, ns))
print("100n / n log n ", ratio(lambda n: 100 * n, lambda n: n * math.log2(n), ns))
print("n^2 / n log n ", ratio(lambda n: n * n, lambda n: n * math.log2(n), ns))
n log n / n^2 [0.332, 0.066, 0.01, 0.001, 0.0]
100n / n log n [30.103, 15.051, 10.034, 7.526, 6.021]
n^2 / n log n [3.01, 15.051, 100.343, 752.575, 6020.6]
Read the middle row: 100n really is smaller than n\log n for every size shown here and will stay a constant factor of about 6 away at n = 10^5 — yet the ratio is falling, and it keeps falling for ever, so 100n \in \mathcal{O}(n\log n) and not the other way round. Constant factors matter in practice; they never decide the order of growth.
The order everything sits in
For any constants c > 1 and k \ge 1:
An exponential beats every power of n, and every power of n beats every power of \log n. So a cost written as c^{n}\,n^{a}\,(\log n)^{b} can be compared with another just by comparing c, then a, then b — in that order, and never by plugging in one value of n. At n = 10, n^{10} dwarfs 2^{n}; at n = 100 it is the other way round.
Sums you will keep needing
Counting the work of a loop nest means adding up a series, and four of them cover most cases:
n = 1000
print(sum(range(1, n + 1)), n * (n + 1) // 2)
print(sum(i * i for i in range(1, n + 1)), n * (n + 1) * (2 * n + 1) // 6)
print(sum(2 ** i for i in range(11)), 2 ** 11 - 1)
500500 500500
333833500 333833500
2047 2047
The first one is why a loop whose inner range grows with the outer index is \Theta(n^2), not \Theta(n): half of n^2 is still n^2.
Recurrences, and the trick of subtracting
A recursive algorithm's cost is a recurrence, and the first move is almost always to write it twice and subtract. Take
which looks expensive because every term depends on all the earlier ones. Write the same equation for T(n-1) and subtract: everything in the sum cancels except one term, leaving T(n) - T(n-1) = T(n-1), that is T(n) = 2\,T(n-1). The closed form is 2^{n}, and nothing had to be guessed:
def slow(n):
if n == 0:
return 1
return 1 + sum(slow(i) for i in range(n))
print([slow(n) for n in range(6)])
print([2 ** n for n in range(6)])
[1, 2, 4, 8, 16, 32]
[1, 2, 4, 8, 16, 32]
For divide and conquer, T(n) = a\,T(n/b) + n^{k}, draw the recursion tree instead. Level i holds a^{i} subproblems of size n/b^{i}, so it costs n^{k}(a/b^{k})^{i}: a geometric series with ratio a/b^{k}. Three cases follow, and you decide between them by comparing the integers a and b^{k}, never by a floating-point logarithm:
| compare | which level dominates | result |
|---|---|---|
| a > b^{k} | the leaves | \Theta(n^{\log_b a}) |
| a = b^{k} | every level equally | \Theta(n^{k}\log n) |
| a < b^{k} | the first combine | \Theta(n^{k}) |
Merge sort is a = 2, b = 2, k = 1, so a = b^{k} and the cost is \Theta(n\log n). Binary search is a = 1, b = 2, k = 0: also balanced, giving \Theta(\log n). Karatsuba multiplication is a = 3, b = 2, k = 1, the leaves win, and the cost is \Theta(n^{\log_2 3}) \approx \Theta(n^{1.585}).
Sorting
The built-in sort
Python's sorted() returns a new list; list.sort() sorts in place and returns None. Both are O(n log n) and both take a key function that says what to compare.
words = ["pear", "Fig", "banana", "kiwi"]
print(sorted(words)) # capital letters sort first
print(sorted(words, key=str.lower)) # case-insensitive
print(sorted(words, key=len)) # by length, ties keep original order
print(sorted(words, key=len, reverse=True))
['Fig', 'banana', 'kiwi', 'pear']
['banana', 'Fig', 'kiwi', 'pear']
['Fig', 'pear', 'kiwi', 'banana']
['banana', 'pear', 'kiwi', 'Fig']
Python's sort is stable: elements that compare equal keep their original relative order. That is why "pear" stays ahead of "kiwi" when sorting by length.
To sort by several fields, return a tuple from the key. Tuples compare element by element, so (age, name) means "by age, and among equal ages by name".
people = [("Bob", 30), ("Alice", 25), ("Carol", 30)]
print(sorted(people, key=lambda p: (p[1], p[0])))
# descending age, ascending name: negate the numeric field
print(sorted(people, key=lambda p: (-p[1], p[0])))
[('Alice', 25), ('Bob', 30), ('Carol', 30)]
[('Bob', 30), ('Carol', 30), ('Alice', 25)]
Common mistakes
nums = nums.sort()setsnumstoNone. Usenums.sort()alone ornums = sorted(nums).- Sorting a list of lists without a key sorts by the first element, then the second, which is sometimes what you want and sometimes a silent bug.
- You cannot negate a string to reverse only that field. Use
reverse=Trueif every field goes the same direction, or sort twice (stable sorts make this work: sort by the secondary key first, then by the primary).
Practice: Sort People by Age, Then Name
How merge sort works
You will almost always call the built-in sort, but you should know how an O(n log n) sort works, and merge sort is the clearest. The idea is divide and conquer:
- A list with 0 or 1 elements is already sorted.
- Otherwise split the list in half, sort each half (recursively), and merge the two sorted halves.
Merging is the important step. Two sorted lists can be combined in one pass by keeping an index into each, repeatedly appending whichever front element is smaller:
def merge(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:]) # only one of these is non-empty
out.extend(b[j:])
return out
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
return merge(merge_sort(nums[:mid]), merge_sort(nums[mid:]))
print(merge([1, 4, 9], [2, 3, 10]))
print(merge_sort([8, 3, 6, 1, 7, 2]))
[1, 2, 3, 4, 9, 10]
[1, 2, 3, 6, 7, 8]
Why O(n log n)? Halving repeatedly produces log n levels of splitting, and at every level the merges together touch every element once, which is O(n) per level. Written as a recurrence, if T(n) is the work to sort n items, then
two sorts of half the size plus one merge over all n items. Each level of halving adds n, and there are \log_2 n levels, so T(n) = n \log_2 n. You can check it by turning the recurrence straight into a function:
import math
def T(n):
return 0 if n <= 1 else 2 * T(n // 2) + n
for n in (8, 1024, 2 ** 20):
print(n, T(n), n * int(math.log2(n)))
8 24 24
1024 10240 10240
1048576 20971520 20971520
Practice: Two Sorted Piles into One, Implement Merge Sort
Quicksort: partition, then recurse
Merge sort splits the list in half and does its work when the halves come back together. Quicksort does the opposite: it does the work first, by partitioning the list around a pivot so that everything smaller is on the left and everything larger on the right, and then sorts the two sides with nothing left to merge.
Lomuto's partition is the one to learn first. Take the last element as the pivot, sweep from left to right, and keep a boundary i such that everything up to i is at most the pivot. Each small element found is swapped up to just past the boundary; at the end the pivot itself is swapped into the gap.
def partition(a, lo, hi):
pivot = a[hi]
i = lo - 1
for j in range(lo, hi):
if a[j] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
return i + 1
def quicksort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return a
p = partition(a, lo, hi)
quicksort(a, lo, p - 1)
quicksort(a, p + 1, hi)
return a
print(quicksort([7, 2, 9, 1, 5]))
print(quicksort([(i * 37) % 11 for i in range(11)]))
[1, 2, 5, 7, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Three things are worth noticing.
It is in place. Merge sort needs a second array to merge into; quicksort needs only the recursion stack, which is why it is the sort most standard libraries reach for.
The pivot decides everything. With the last element as the pivot, an already sorted list is the worst case: each partition peels off a single element, the recursion runs n deep and the cost is \Theta(n^2). A list of equal values is just as bad. Picking the middle element, or the median of the first, middle and last, fixes both of the cases that occur in practice; picking at random makes the bad case unlikely rather than impossible.
It is not stable. Records that compare equal can come out in the other order, because the partition throws elements across the list:
records = [(2, "a"), (1, "b"), (2, "c"), (1, "d")]
def qsort(a, lo, hi):
if lo >= hi:
return
pivot = a[hi][0]
i = lo - 1
for j in range(lo, hi):
if a[j][0] <= pivot:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[hi] = a[hi], a[i + 1]
qsort(a, lo, i)
qsort(a, i + 2, hi)
mine = list(records)
qsort(mine, 0, len(mine) - 1)
print("quicksort:", mine)
print("sorted: ", sorted(records, key=lambda r: r[0]))
quicksort: [(1, 'b'), (1, 'd'), (2, 'c'), (2, 'a')]
sorted: [(1, 'b'), (1, 'd'), (2, 'a'), (2, 'c')]
Of the classic sorts, bubble sort, insertion sort and merge sort are stable; selection sort and quicksort are not. That matters when you sort by one field and then another: only a stable sort keeps the first ordering inside the ties of the second.
| sort | comparisons average | comparisons worst | extra memory | stable |
|---|---|---|---|---|
| bubble | \Theta(n^2) | \Theta(n^2) | \Theta(1) | yes |
| insertion | \Theta(n^2) | \Theta(n^2) | \Theta(1) | yes |
| selection | \Theta(n^2) | \Theta(n^2) | \Theta(1) | no |
| merge | \Theta(n\log n) | \Theta(n\log n) | \Theta(n) | yes |
| quicksort | \Theta(n\log n) | \Theta(n^2) | \Theta(\log n) | no |
| heapsort | \Theta(n\log n) | \Theta(n\log n) | \Theta(1) | no |
Insertion sort's quadratic worst case is not the whole story: it makes only n - 1 comparisons on an already sorted list and is the fastest thing there is on a few dozen elements, which is why real library sorts switch to it for small ranges.
Binary search
If a list is sorted, comparing the target with the middle element tells you which half it must be in. Discard the other half and repeat. Each step halves the range, so n elements need about \log_2 n steps: a million elements need only about 20, because 2^{20} \approx 10^6. A linear scan may need all n. Press Run to compare the worst cases:
ns = [2 ** k for k in range(1, 21)]
plot(ns, ns, label="linear search", logx=True, logy=True, xlabel="list length n", ylabel="steps in the worst case")
plot(ns, [n.bit_length() for n in ns], label="binary search") # floor(log2 n) + 1
The template
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1 # inclusive bounds
while lo <= hi: # range is non-empty
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1 # target is strictly to the right
else:
hi = mid - 1 # target is strictly to the left
return -1
print(binary_search([1, 3, 5, 7, 9, 11], 7))
print(binary_search([1, 3, 5, 7, 9, 11], 4))
3
-1
Off-by-one pitfalls
Nearly every binary search bug is one of these:
hi = len(nums)withwhile lo <= hi. Thenmidcan equallen(nums)and you get anIndexError. Decide up front whetherhiis inclusive (len(nums) - 1, loop whilelo <= hi) or exclusive (len(nums), loop whilelo < hi) and stay consistent.lo = midorhi = midin the inclusive template. Whenloandhiare one apart,midequalslo, andlo = midchanges nothing: an infinite loop. In the inclusive template always move pastmid(mid + 1ormid - 1).- Returning
lowithout checking. When the loop ends,lois where the target would be inserted, which is useful (see below) but is not proof that the target is present.
Finding a boundary (lower bound)
Plain binary search stops at any match. With duplicates, you often want the first index whose value is >= target. This variant uses an exclusive hi and never skips mid, because mid itself might be the answer:
def lower_bound(nums, target):
lo, hi = 0, len(nums) # hi is exclusive
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1
else:
hi = mid # mid could be the answer; keep it
return lo
nums = [1, 2, 4, 4, 4, 7]
print(lower_bound(nums, 4)) # first 4
print(lower_bound(nums, 5)) # where 5 would be inserted
print(lower_bound(nums, 9)) # len(nums): past the end
2
5
6
Note it does not loop forever: when lo < hi, mid is strictly less than hi, so hi = mid always shrinks the range. lower_bound answers the "search insert position" problem directly, and the standard library ships it as bisect.bisect_left(nums, target). The last occurrence of a value is lower_bound(nums, target + 1) - 1.
Binary search on the answer
Sometimes there is no list at all, just a range of candidate answers where some check is false up to a point and true afterwards. Integer square root is the classic example: find the largest k with k * k <= n.
def isqrt(n):
lo, hi = 0, n
while lo <= hi:
mid = (lo + hi) // 2
if mid * mid <= n:
lo = mid + 1 # mid works; try bigger
else:
hi = mid - 1
return hi # last value that worked
print([isqrt(x) for x in (0, 1, 8, 9, 10, 99, 100)])
[0, 1, 2, 3, 3, 9, 10]
The same shape solves "minimum speed to finish in time", "smallest capacity to ship in d days" and many others: if you can write an is_ok(mid) check that flips from false to true exactly once, binary search finds the flip point.
Practice: Binary Search, Where a Repeated Mark Begins and Ends, Searching a Turned Dial
Interactive problems
Binary search does not need an array. All it needs is a question that splits the remaining candidates in two. In an interactive problem the data is hidden behind an oracle, a function you call with a question and that answers it, and you are allowed only a limited number of questions. The grader counts them.
Each yes/no answer can at best halve the candidates, so finding one of n possibilities needs at least ⌈log2 n⌉ questions, and a well-placed question in the middle achieves exactly that. Here the oracle answers "higher", "lower" or "yes":
def make_oracle(secret, limit):
asked = []
def compare(guess):
# "higher" if the secret is bigger than the guess, "lower" if smaller, "yes" if equal
asked.append(guess)
if len(asked) > limit:
raise RuntimeError("too many questions")
return "yes" if guess == secret else "higher" if secret > guess else "lower"
return compare, asked
def guess_number(n, compare):
lo, hi = 1, n
while True:
mid = (lo + hi) // 2
answer = compare(mid)
if answer == "yes":
return mid
if answer == "higher":
lo = mid + 1
else:
hi = mid - 1
compare, asked = make_oracle(secret=73, limit=7)
print(guess_number(100, compare), asked)
73 [50, 75, 62, 68, 71, 73]
The general recipe: keep the set of candidates that are still consistent with every answer so far, and ask the question whose answers split that set as evenly as possible. With three possible answers (a balance scale: left heavier, right heavier, equal) each question can split three ways, so ⌈log3 n⌉ questions are enough.
Common mistakes: asking a question you already know the answer to (it wastes the budget). Off-by-one ranges that lose the answer: after "higher" the secret is in mid + 1 .. hi. Asking one more question after you already know the answer.
Practice: Leak in the Pipeline, The Buried Time Capsule, The Hollow Ring
Two pointers
Two pointers means walking a list with two indices instead of one, so that a problem about pairs of elements is solved in a single pass rather than a nested loop. There are two flavours.
Opposite ends, moving inward
Used on sorted input, or when the answer depends on the width between the pointers. Start with left = 0, right = len - 1 and, at each step, decide which pointer to move based on the current pair.
def two_sum_sorted(numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
s = numbers[left] + numbers[right]
if s == target:
return [left, right]
if s < target:
left += 1 # need a bigger sum: only moving left helps
else:
right -= 1 # need a smaller sum
return None
print(two_sum_sorted([1, 3, 4, 6, 8, 11], 10))
[2, 3]
The justification matters: because the list is sorted, if the sum is too small then every pair using the current left is also too small (the current right is the largest partner available), so left can safely move on. The same style of argument drives Rain Tank Between Two Posts, where you always move the shorter post because the taller one cannot improve the result.
Same direction (read / write)
Here both pointers move rightwards: one reads, one writes. This is how you modify a list in place without allocating a new one. Removing duplicates from a sorted list:
def remove_duplicates(nums):
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return write # number of unique elements
nums = [1, 1, 2, 3, 3, 3, 4]
k = remove_duplicates(nums)
print(k, nums[:k])
4 [1, 2, 3, 4]
Merging two sorted lists (from the sorting section) is the same idea with one reader on each input.
Common mistakes
- Using
while left <= rightwhen the two pointers must refer to different elements (it letsleft == right, pairing an element with itself). - Forgetting to skip duplicates in 3Sum, producing the same triplet twice. After finding a match, advance
leftwhilenums[left] == nums[left - 1].
Practice: Two Entries That Explain the Gap, Rain Tank Between Two Posts, Trios That Cancel to Zero
Sliding window
A sliding window is a two-pointer variant for contiguous subarrays or substrings. The window is nums[left:right+1]; you move right to grow it and left to shrink it, keeping some summary of the contents (a sum, a count, a set) updated in O(1) rather than recomputed.
Fixed size
When the window is always k wide, each move adds one element and drops one:
def max_sum_window(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # enters, leaves
best = max(best, window)
return best
print(max_sum_window([3, 8, 1, 2, 7, 4, 1], 3))
13
Variable size
When the window must satisfy a rule (no repeated characters, sum at most s, at most two distinct values), expand right every iteration and shrink from left only as long as the rule is broken:
def longest_unique(s):
seen = set()
left = best = 0
for right, ch in enumerate(s):
while ch in seen: # rule broken: shrink until fixed
seen.remove(s[left])
left += 1
seen.add(ch)
best = max(best, right - left + 1)
return best
print(longest_unique("notebook"), longest_unique("mississippi"))
5 3
Some problems flip the direction: the window is valid once it is big enough, and you want the shortest valid one. Then you shrink while the window is still valid, recording the length each time. Minimum size subarray with sum at least target (positive numbers only):
def min_subarray_len(target, nums):
best = float("inf")
left = window = 0
for right, x in enumerate(nums):
window += x
while window >= target: # valid: try to make it shorter
best = min(best, right - left + 1)
window -= nums[left]
left += 1
return 0 if best == float("inf") else best
print(min_subarray_len(9, [1, 4, 2, 2, 5, 4, 1]))
2
Both are O(n) because left and right each move at most n times in total, even though there is a loop inside a loop.
Common mistakes
- Moving
leftbackwards. The window only ever slides right; if you "reset"leftto an earlier position you lose the O(n) guarantee and usually the correctness too. - Sliding windows need a monotonic quantity. With negative numbers, adding an element can make the sum go down, so "shrink while sum >= target" breaks. That is where prefix sums come in.
Practice: Best Run of k Market Days, Longest Typing Run Without a Repeat
Prefix sums
A prefix-sum array stores running totals: prefix[i] is the sum of the first i elements, with prefix[0] = 0. Build it once in O(n) and any range sum becomes a subtraction:
nums = [3, 1, 4, 1, 5, 9]
prefix = [0]
for x in nums:
prefix.append(prefix[-1] + x)
print(prefix)
def range_sum(left, right): # inclusive
return prefix[right + 1] - prefix[left]
print(range_sum(1, 3), sum(nums[1:4]))
print(range_sum(0, 5), sum(nums))
[0, 3, 4, 8, 9, 14, 23]
6 6
23 23
In maths notation, for a list a_0, a_1, \dots, a_{n-1} the prefix sums are
and the sum from a_l to a_r is P_{r+1} - P_l: everything up to r minus everything before l. That subtraction is all range_sum does.
The leading 0 is what makes range_sum(0, r) work without a special case; the array has one more entry than nums.
Prefix sums plus a hash map
"How many subarrays sum to k?" is a pairs question in disguise: nums[i..j] sums to k exactly when prefix[j+1] - prefix[i] == k. Walking left to right with a running sum, you want to know how many earlier prefix sums equal running - k, which a Counter answers in O(1). This works with negative numbers, which the sliding window could not handle.
from collections import Counter
def subarray_sum(nums, k):
seen = Counter({0: 1}) # the empty prefix
running = count = 0
for x in nums:
running += x
count += seen[running - k] # look up first...
seen[running] += 1 # ...then record
return count
print(subarray_sum([2, 1, 3, 4], 4), subarray_sum([1, -1, 0], 0))
2 3
Common mistakes
- Recording
runningbefore looking uprunning - kwhenk == 0: that counts the empty subarray at every position. - Forgetting
{0: 1}, which drops every subarray that starts at index 0.
Practice: Ledger Totals Between Two Days, Stretches With an Exact Net Change
Kadane's algorithm
"Find the contiguous subarray with the largest sum" has O(n²) subarrays, but the best subarray ending at position i is easy to describe: either nums[i] alone, or nums[i] extended from the best subarray ending at i - 1. Whenever the running total would drag nums[i] down, start fresh.
def max_subarray(nums):
current = best = nums[0]
for x in nums[1:]:
current = max(x, current + x) # extend or restart
best = max(best, current)
return best
print(max_subarray([3, -5, 2, 6, -4, 5, -9, 1]))
print(max_subarray([-3, -1, -2]))
9
-1
In symbols, if c_i is the best sum of a subarray that ends at position i, then c_i = \max(a_i,\ c_{i-1} + a_i), and the answer is the largest c_i over all i. The variable current holds c_i and best holds the largest one so far.
This is your first taste of dynamic programming: each step reuses the answer to a smaller version of the same question. Two things to notice. best is tracked separately because current can drop after the maximum has been seen. And initialising both to nums[0] rather than 0 is what makes an all-negative input return the least-bad element instead of 0. If you need the subarray itself, remember the index where current was last restarted.
Practice: Best Streak in a Profit Log (Kadane's Algorithm)
Intervals
Interval problems (meeting rooms, merging bookings, inserting a new range) share one first move: sort by start. Once sorted, an interval can only overlap the interval placed just before it in the output, so a single pass with a comparison against merged[-1] is enough.
def merge_intervals(intervals):
merged = []
for start, end in sorted(intervals):
if merged and start <= merged[-1][1]: # overlaps the last one
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
print(merge_intervals([[9, 12], [2, 5], [4, 7], [20, 21]]))
print(merge_intervals([[3, 6], [6, 8], [4, 5]]))
[[2, 7], [9, 12], [20, 21]]
[[3, 8]]
Two intervals [a, b] and [c, d] (with a <= c) overlap when c <= b. Use max when extending, because the new interval might end before the current merged one does ([1, 10] followed by [2, 3]). Whether touching intervals like [3, 6] and [6, 8] count as overlapping is a problem-specific rule; read the statement.
Practice: Merging Bookings for One Room
Matrices: keeping bounds straight
Matrix traversal problems (spiral order, rotate image, set zeroes) are rarely about a clever algorithm. They are about tracking boundaries carefully. For a spiral, keep top, bottom, left, right, walk each edge with a range(), and shrink the boundary you just walked. The subtle part is the last lap: once the unvisited region is a single row or column, the "bottom row" walk would repeat the "top row" walk unless you check top <= bottom again before doing it.
Two idioms worth memorising: range(right, left - 1, -1) walks leftwards inclusive of left, and list(zip(*matrix)) transposes a matrix, which combined with reversing each row rotates it 90 degrees clockwise.
matrix = [[1, 2, 3], [4, 5, 6]]
print([list(row) for row in zip(*matrix)])
print([list(row)[::-1] for row in zip(*matrix)])
[[1, 4], [2, 5], [3, 6]]
[[4, 1], [5, 2], [6, 3]]
Practice: Spiral Walk Round a Seed Tray
Checklist
Before moving to Phase 4, make sure you can do each of these without looking anything up:
- Explain why an O(n log n) algorithm beats an O(n²) one, and estimate which one a piece of code is by counting nested loops.
- Sort a list of records by two fields using
sorted()with a tuple key, including one field descending. - Describe how merge sort splits and merges, and write the merge step with two pointers.
- Write binary search from memory with inclusive bounds, and say why
lo = mid + 1(notlo = mid) is required. - Write the lower-bound variant and use it to find the first and last occurrence of a value.
- Apply binary search to a rotated sorted array by identifying which half is sorted.
- Recognise when two pointers from opposite ends apply, and justify which pointer to move.
- Slide a fixed-size window by adding the entering element and subtracting the leaving one.
- Grow and shrink a variable-size window while maintaining a set or count of its contents.
- Build a prefix-sum array with a leading
0and answer a range sum in O(1). - Count subarrays with a given sum using prefix sums and a hash map, including negative numbers.
- State Kadane's recurrence (
current = max(x, current + x)) and handle all-negative input. - Merge overlapping intervals after sorting by start.
- Walk a matrix in spiral order without visiting any cell twice.
- Solve an interactive problem within ⌈log2 n⌉ questions by always asking the question that halves the candidates.