You’ve practiced two patterns for problems built from a sequence of choices:
- Backtracking builds every candidate one choice at a time with a shared path, undoes each choice with a matching
pop(), and records a copy when a candidate is complete. Pruning partial answers that can’t work, and building each combination in one order, keeps the search close to the size of its output. - Dynamic programming names the smaller question that keeps coming up, answers it once, and builds bigger answers from a
Mapor a table. The cost is the number of states times the work per state, which turns exponential searches into polynomial ones.
Things to Remember in an Interview
- Ask first whether the problem wants every option or just a count or best value. Listing calls for backtracking, while counting and optimizing usually call for dynamic programming.
- Say the state out loud before you code: “the fewest stamps for exactly this amount” or “the routes into this cell.”
- Push
[...path], notpath, and key aSetorMapwith strings or numbers, never with arrays. - Start counts at
1nwhen they can passNumber.MAX_SAFE_INTEGER, useInfinityfor impossible states, and build 2D tables withArray.from(). - Prefer a loop over deep recursion when the input can be thousands of steps long.