Dynamic programming with explicit states
Quick answer
Dynamic programming (DP) saves solutions of reusable subproblems. Define a state, recurrence, base values and evaluation order before implementing a table or memoized recursion.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const dp=[1,1];for(let i=2;i<=5;i++)dp[i]=dp[i-1]+dp[i-2];console.log(JSON.stringify(dp));Expected console output:
[1,1,2,3,5,8]Each state combines the two possible final moves.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
function ways(n){ if(n<2)return 1; let a=1,b=1; for(let i=2;i<=n;i++) [a,b]=[b,a+b]; return b;}console.log(ways(0),ways(4),ways(6));Expected console output:
1 5 13Only the two previous counts are needed.
How it works and cost model
For counting ways to climb n stairs with moves of one or two, define dp[i] as the number of sequences reaching step i. dp[0]=1 counts the empty sequence, dp[1]=1, and dp[i]=dp[i-1]+dp[i-2] for i>=2. Last moves partition the possibilities into disjoint groups. Compute bottom-up in O(n) additions and O(n) table cells, or keep only two previous values for O(1) scalar space. Limit n to 40 here to keep counts within Number safe-integer bounds. The same approach can minimize costs if the state and recurrence encode the actual objective.
Common mistakes
Do not set dp[0] to zero without checking what the state means. A memo table must key all relevant inputs; not every recursive problem benefits from memoization.
Practice
Count ways for n=0,1,2,5 using the table, then implement two-scalar state and compare outputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dynamic programming with explicit states — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
What does dp[0] = 1 represent in the stair-counting problem?
Why can the staircase DP table be replaced with two scalar values?
What must a DP state contain?
What is the exact console output in the Dynamic programming state recurrence example 1?
const dp=[1,1];for(let i=2;i<=5;i++)dp[i]=dp[i-1]+dp[i-2];console.log(JSON.stringify(dp));What is the exact console output in the Dynamic programming state recurrence example 2?
function ways(n){ if(n<2)return 1; let a=1,b=1; for(let i=2;i<=n;i++) [a,b]=[b,a+b]; return b;}console.log(ways(0),ways(4),ways(6));