Dynamic Programming

Data Structures & Algorithms · Greedy & Dynamic Programming · Intermediate · 18 min

Remember answers to small problems so you never solve them twice.

A row of boxes on a shelf, filled from left to right. Each new box is computed by peeking into one or two boxes just before it, so nothing is ever worked out twice. The last box holds the answer.

The idea in everyday words

If I ask you 1+1+1+1+1 you count: 5. If I add '+1' at the end, you don't recount: you say 6 instantly because you REMEMBERED 5. Dynamic Programming is just recursion + a memory notebook.

When is it DP?

  • The problem asks for count of ways, min/max cost, or is it possible.
  • Big answer is built from smaller overlapping answers.

Climbing stairs (1 or 2 steps at a time): ways(n) = ways(n-1) + ways(n-2). Without memory this repeats work exponentially!

Recipe (say this in interviews)

  1. State: what does dp[i] mean? ("ways to reach step i")
  2. Transition: dp[i] = dp[i-1] + dp[i-2]
  3. Base cases: dp[0] = 1, dp[1] = 1
  4. Order: fill from small to big
  5. Answer: dp[n]

Step by step

  1. dp[0]=1, dp[1]=1:

    One way to stand still, one way to reach step 1.

  2. dp[2]:

    dp[1] + dp[0] = 2 (1+1, 2)

  3. dp[3]:

    dp[2] + dp[1] = 3

  4. dp[4]:

    dp[3] + dp[2] = 5

  5. Pattern:

    It's Fibonacci! O(n) instead of O(2ⁿ).

Code example

from functools import lru_cache

@lru_cache(maxsize=None)          # top-down: recursion + memory
def ways(n):
    if n <= 1:
        return 1
    return ways(n - 1) + ways(n - 2)

def ways_table(n):                # bottom-up table
    dp = [1, 1] + [0] * (n - 1)
    for i in range(2, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[n]

print(ways(10), ways_table(10))

Complexity

  • Time: O(n)
  • Space: O(n) table, O(1) with two variables

Interview tips

  • Classic DP list: climbing stairs, house robber, coin change, longest common subsequence, knapsack.

  • Always explain state + transition before coding.

  • Mention you can optimise space if only previous rows are needed.

Challenge: House Robber

Houses in a row hold money. You can't rob two adjacent houses. Return the max money you can rob.

Example: rob([2, 7, 9, 3, 1]) → 12 (2 + 9 + 1)

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Greedy & Dynamic Programming

Previous: Greedy & Intervals · Next: 2D Dynamic Programming