Dynamic Programming Easy
Climbing Stairs: Solution and Approach
You climb a staircase of n steps, taking 1 or 2 steps at a time. In how many distinct ways can you reach the top?
Similar questions reported in: TCS, Infosys, Accenture, Amazon
Example
- Input:
- n = 4
- Output:
- 5
Brute force first
Plain recursion ways(n) = ways(n - 1) + ways(n - 2) recomputes the same values again and again, so it takes O(2ⁿ) time.
The better idea
To reach step n, your last move came from step n - 1 or step n - 2. So ways(n) = ways(n - 1) + ways(n - 2), the Fibonacci pattern. Build it from the bottom and keep only the last two values.
Steps
- If n <= 2, return n.
- Set a = 1 (ways to reach step 1) and b = 2 (ways to reach step 2).
- For steps 3 to n: set a, b = b, a + b.
- Return b.
Code
def climb_stairs(n):
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return bpublic int climbStairs(int n) {
if (n <= 2) return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}Complexity
Time: O(n)
Space: O(1)
Edge cases to test
- n = 1 gives 1 and n = 2 gives 2.
- For large n the count grows fast. In Java, use long once n goes above about 45.
Interview follow-up: Explain how this is the simplest dynamic programming problem: a state, a transition and base cases.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.