Problem
Count the number of distinct ways to reach step n when each move can be either 1 step or 2 steps.
Base Cases
- n = 1 → exactly 1 way: take a single 1-step.
- n = 2 → exactly 2 ways: 1 + 1 (two 1-steps) or 2 (one 2-step).
Key Insight (Recurrence)
Let Ways(i) denote the number of ways to reach step i.
To reach step i, you must come either from step i − 1 (taking 1 step) or from step i − 2 (taking 2 steps):
Ways(i) = Ways(i − 1) + Ways(i − 2) (Fibonacci pattern).
Iterative DP with Rolling State
We avoid building an entire DP array because only the two most recent values are required. We initialize with the base cases:
- prevWays = 1 → represents
Ways(1). - currentWays = 2 → represents
Ways(2).
For each step i from 3 to n:
- At the start of iteration i:
currentWaysholds Ways(i − 1) (the number of ways to reach step i − 1).prevWaysholds Ways(i − 2) (the number of ways to reach step i − 2).
-
We then compute
nextWays = currentWays + prevWays, which represents the number of ways to reach step i (Ways(i)). -
After this calculation, we roll the state forward:
- currentWays ←
Ways(i)(just computed asnextWays). - prevWays ←
Ways(i − 1)(the oldcurrentWays).
- currentWays ←
👉 This reassignment ensures that at the end of each iteration, the variables still correctly represent Ways(i − 1) and Ways(i), where i is the latest step index processed.
Termination & Output
The loop runs for i = 3 … n. When it finishes, the most recent step is n, so
currentWays = Ways(n).
📌 The final answer is in currentWays because, by construction, it always tracks the number of ways to reach the latest step.