Interview conceptCoding & Algorithms

Dynamic Programming And Memoization

Asked of: Software Engineer

Last updated

A five-step visual trace shows Fibonacci recursion revisiting the same states, memoization caching them, and bottom-up dynamic programming filling one table.

What's being tested

These problems test dynamic programming: defining a state, deriving a recurrence, choosing correct base cases, and evaluating overlapping subproblems efficiently. You must distinguish ordered versus unordered counting, unlimited versus single-use choices, and state dimensions such as position, capacity, or transaction count.

Patterns & templates

  • One-dimensional counting DP: dp[sum] += dp[sum - value]; iterate candidate values inside the sum loop when order should not matter.
  • For ordered sequences, iterate totals first and choices second; dp[target] = Σ dp[target - x], with dp[0] = 1.
  • Subsequence counting uses dp[i][j] for source/target prefixes: match contributes take-or-skip; time O(mn), space reducible to O(n).
  • 0/1 knapsack uses take-or-skip; iterate capacity downward in a one-dimensional table to prevent reusing an item.
  • Memoization caches recursive states only when first visited; typically changes exponential recursion to O(number of states × transitions).
  • Stock trading can use constant-size state compression: track cash/hold after each of two completed transactions, handling buy-before-sell ordering.
  • Use 64-bit counts where results can exceed 32-bit limits; define unreachable states carefully and state whether modulo arithmetic is required.

Common pitfalls

Pitfall: Reversing loop order changes whether permutations count separately or whether each item can be reused.

Pitfall: Setting dp[0] = 0 breaks counting recurrences; the empty sequence is usually one valid way to form sum zero.

Pitfall: Claiming memoization is always O(n) without identifying the state dimensions, transition count, and memory usage.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts