Interview concept

What is dynamic programming?

Dynamic programming solves a problem by combining solutions to overlapping subproblems, storing each result once so it is never recomputed. It applies when a problem has optimal substructure and overlapping subproblems.

Interview concept

How it works

Memoization vs tabulation

Top-down memoization caches recursive results; bottom-up tabulation fills a table iteratively.

Define the state

Identify what parameters uniquely describe a subproblem and write the recurrence relating states.

Common patterns

Knapsack, longest common subsequence, edit distance, and grid path problems are frequent DP templates.

Interview concept

Worked example: fewest coins for 6 with coins 1, 3, and 4

Coin change is the classic case where a greedy choice fails and dynamic programming does not.

Define the state

dp[a] is the fewest coins that make amount a, with dp[0] = 0.

Write the recurrence

dp[a] = 1 + the minimum of dp[a - c] over every coin c no larger than a.

Fill the table

dp[1] = 1, dp[2] = 2, dp[3] = 1, dp[4] = 1, dp[5] = 2 (4 + 1), dp[6] = 2 (3 + 3).

Compare with greedy

Greedy takes 4 first and ends with 4 + 1 + 1, three coins, so the table shows why greedy is wrong here.

State the cost

O(amount x number of coins) time and O(amount) space.

Interview concept

Responsible use

Use any live AI assistant only where interview, workplace, school, and platform rules allow it. Do not use generated answers to misrepresent your skills, experience, or authorship.

FAQ

Common questions.

When should I use dynamic programming?

Use it when a problem has optimal substructure and overlapping subproblems, so cached results avoid exponential recomputation.

How do I find the DP state?

Ask what minimal set of parameters describes a subproblem, then write a recurrence that builds larger states from smaller ones.