Chapter 15 ยท Dynamic Programming and Interview Patterns
Interview Patterns in Motion
Five templates that turn an O(nยฒ) or "try every answer" problem into a linear scan or a logarithmic search. Pick one, type your own input, and predict each move before it happens.
How to read this
- The top row is your input with indices underneath. Arrows mark the pointers (
l,r,i); the orange bracket is the current window or range. - Colors: blue = the pointer's current element, yellow = being compared or inside the window, red = just changed / popped / written, green = part of the answer, gray = ruled out forever.
- The lower half is the pattern's helper: the running sum, the hash map of last positions, the stack, the prefix-sum table with its counts, or the lo/mid/hi number line with the day-by-day packing.
- Every counter panel shows the pattern's work next to the brute-force cost it replaces. The pointers only move forward, which is the amortized argument for O(n).
Try this
- Two pointers on
1 3 4 6 8 11, target 10: five sum checks find (2, 3) = 4 + 6. Brute force would test up to 15 pairs. Try target 100: l and r meet after 5 checks with no pair. - Longest substring on
abacdbe: l jumps from 0 to 1 at the second "a", then past the first "b" to 2; the answer is 5 ("acdbe"). Tryaaaa(answer 1) andabcdef(answer 6, l never moves). - Shortest window โฅ S on
4 1 1 3 2 5, S = 8: best becomes 4, then 3 (3 2 5). Count pointer moves: never more than 2n = 12. - Next greater on
3 7 1 4 2 6โ7 โ1 4 6 6 โ1. When 6 arrives it pops two indices at once. Try a decreasing array: nothing is popped until the end, and every answer is โ1. - Prefix sums on
1 2 1 โ1 2 1, k = 3: count 5. Binary search on the answer for4 8 2 5 3 7 1, D = 3: mids 19, 13, 10, 12, 11 and the answer is 12 after only 5 checks; the range [8, 30] holds 23 candidates, and doubling the weights barely adds a check.
Go deeper
๐ Lesson 15 ยท Part A
๐๏ธ Chapter 15 Arena
๐งฉ two-sum-sorted
๐งฉ longest-unique-substring
๐งฉ min-subarray-len
๐งฉ next-greater-element
๐งฉ subarray-sum-k
๐งฉ ship-within-days
๐งฉ sliding-window-max
๐ฎ Binary search (search-lab)
๐ฎ Segment tree & Fenwick
๐ฎ Amortized analysis
๐ฎ Dynamic Programming (DP) Studio