Skip to the page

Dynamic programming · mid

Dynamic programming in JavaScript: the intro

Dynamic programming builds the answer from smaller overlapping sub-problems, top-down with memoised recursion or bottom-up with a table, once you can write the recurrence and the base cases. In JavaScript, prefer bottom-up for large n (deep recursion throws RangeError), and watch number precision when counts grow.

The notes

What you must know

  • Signs of DP: 'count the ways', 'minimum/maximum cost', choices at each step, and the same sub-problem appearing many times.
  • Steps: define the state (dp[i] = answer for the first i items or amount i), write the recurrence, set base cases, choose the order, then optimise memory.
  • Climbing stairs: dp[i] = dp[i − 1] + dp[i − 2]. House robber: dp[i] = max(dp[i − 1], dp[i − 2] + a[i]). Both need only two variables.
  • Coin change (min coins): dp[a] = min(dp[a − c] + 1); unreachable stays Infinity → return -1. 'Number of ways' loops coins outside amounts to avoid counting orders twice.
  • LIS: O(n²) DP first, then O(n log n) with a tails array and binary search.
  • Greedy is not DP: greedy coin choice fails for coins [1, 3, 4] and amount 6.
  • Numbers are 64-bit floats: whole numbers are exact only up to 2^53 - 1 (Number.MAX_SAFE_INTEGER). Large 'number of ways' answers lose precision without any error, so apply the problem's modulo (10^9 + 7) at each step, or use BigInt.
  • With a modulo, a * b can reach about 10^18 before the %, which is above 2^53 and gives a wrong result. Use BigInt for that product (BigInt(a) * BigInt(b) % MOD).

The red pen

Common traps: mistake → fix

  • Mistake: Greedy works for coin change

    Fix: only for special coin systems.

  • Mistake: Memoisation and tabulation give different answers

    Fix: same recurrence, different order; tabulation avoids recursion depth.

  • Mistake: Return dp[amount] directly

    Fix: Infinity must become -1.

  • Mistake: A JavaScript number holds any whole number exactly

    Fix: only up to 2^53 - 1; above that, answers are silently wrong.

Easy to hard

Questions interviewers ask, easy to hard

  1. Climbing stairs: how many ways?
  2. House robber; then the circular version.
  3. Minimum coins for an amount; then the number of ways.
  4. Minimum cost for tickets (1-, 7-, 30-day passes).
  5. Longest increasing subsequence in O(n log n).

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview