Courses / Computer Science I
Algorithmics

Dynamic Programming Intuition

Computer Science I 255 words Free to read

Remembering Subproblems

Dynamic programming (DP) is a technique for problems that break into overlapping subproblems — the same smaller problem is needed many times. The core idea is simple: solve each subproblem once and store its answer, then reuse the stored answer instead of recomputing it.

The classic motivation is the naive recursive Fibonacci: F(n)=F(n1)+F(n2)F(n) = F(n-1) + F(n-2). Computed by plain recursion, F(5)F(5) recomputes F(3)F(3) twice, F(2)F(2) three times, and the redundant work explodes exponentially. But there are only nn distinct subproblems (F(0)F(0) through F(n)F(n)). Storing each as it is computed collapses the cost to O(n)O(n).

DP comes in two styles that compute the same thing:

DP applies when a problem has two features: overlapping subproblems (the same subproblem recurs) and optimal substructure (an optimal solution is built from optimal solutions of its subproblems). Classic DP problems include shortest paths, edit distance, the knapsack problem, and longest common subsequence — each turning an exponential brute force into a polynomial-time solution by remembering subresults.

Common pitfall: confusing dynamic programming with plain divide-and-conquer. Divide-and-conquer suits problems whose subproblems are independent (like merge sort's two halves). DP is for problems whose subproblems overlap — where the whole point is to store and reuse answers rather than recompute them.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

10practice questions
2interactive scenes
Start Computer Science I free

Algorithmics