Count the ways to climb stairs with one- and two-step moves using rolling dynamic programming in Java and Python.
Problem and input contract
The input is an integer n ≥ 0. Return the exact number of ordered move sequences that land on step n. For example, a move of one followed by a move of two differs from the reverse order.
n = 0 gives 1 (the empty sequence). n = 1 gives 1. n = 3 gives 3.
Worked example
For n = 3, the sequences are 1+1+1, 1+2 and 2+1.
There is one way to stand at step 0 and one way to reach step 1. Step 2 has two paths. Step 3 has three paths, because it can follow either of the two paths to step 2 or the one path to step 1.
How the solution works
A path ends with either a one-step or a two-step move. Adding the counts for those two preceding positions covers all paths exactly once. There is one empty path for zero stairs.
The two running counts are enough because each new value depends only on the previous two. Java uses BigInteger for exact results. Both versions perform O(n) additions and retain two counts, but the integers themselves grow with n.
Python solution
def climb_stairs(n):
previous, current = 1, 1
for _ in range(2, n + 1):
previous, current = current, previous + current
return currentJava solution
import java.math.BigInteger;
class Solution {
static BigInteger climbStairs(int n) {
BigInteger previous = BigInteger.ONE;
BigInteger current = BigInteger.ONE;
for (int step = 1; step < n; step++) {
BigInteger next = previous.add(current);
previous = current;
current = next;
}
return current;
}
}Approaches and complexity
The recursive version adds the results for n − 1 and n − 2 and repeatedly solves the same subproblems. A table avoids recomputation using O(n) stored counts. Rolling dynamic programming needs just the two latest counts. The exact counts have Θ(n) bits near the end, so the implementation uses Θ(n²) bit operations for the additions and Θ(n) bits of working storage. Fast doubling is a follow-up for large inputs.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Naive recursion | Exponential | O(n) stack | Direct recurrence | Repeats subproblems | Small demonstrations |
| Rolling DP | O(n) additions | Θ(n) bits | Keeps two counts | Large integers still grow | Typical interview solution |
Common mistakes and interview follow-up
Starting with zero ways at step 0 breaks the recurrence. Use one empty sequence, and use arbitrary-precision integers when counts can exceed fixed-width types.
Related practice: Longest Palindromic Substring: Explained with Java and Python Code.
Comments
Post a Comment