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

Try this

  1. 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.
  2. 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"). Try aaaa (answer 1) and abcdef (answer 6, l never moves).
  3. 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.
  4. 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.
  5. Prefix sums on 1 2 1 โˆ’1 2 1, k = 3: count 5. Binary search on the answer for 4 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