πDay 8. Ways to Reach the n'th Stair π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
There are n stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Your task is to count the number of ways the person can reach the top (order matters).
π Example Walkthrough:
Example 1:
Input:
n = 1Output:
1Explanation:
There is only one way to climb 1 stair β just one step of size 1.
Example 2:
Input:
n = 2Output:
2Explanation:
There are two ways to reach the 2nd stair:
(1, 1)
(2)
Example 3:
Input:
n = 4Output:
5Explanation:
There are five ways to climb 4 stairs:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1)
(2, 2)
Constraints:
$(1 \le n \le 44)$
π― My Approach:
Iterative (Space-Optimized DP)
We know this is essentially the Fibonacci sequence shifted by one index.
Use two variables
aandbto track the ways to climb(n-1)andnstairs.Initially,
a = 1andb = 1, representing ways to climb0or1stairs.Update in a loop from
2ton, computingb = a + b(the sum of ways to climb(n-1)and(n-2)), then shiftato the oldb.
This approach eliminates the need for an entire DP array and uses only constant space.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n), as we iterate from 2 to n once.Expected Auxiliary Space Complexity:
O(1), since we only use a constant amount of extra space (two variables).
π Solution Code
Code (C++)
class Solution {
public:
long long countWays(int n) {
long long a = 1, b = 1;
for (int i = 2; i <= n; i++)
tie(a, b) = make_tuple(b, a + b);
return b;
}
};Code (Java)
class Solution {
public long countWays(int n) {
long a = 1, b = 1;
while (n-- > 1) {
b += a;
a = b - a;
}
return b;
}
}Code (Python)
class Solution:
def countWays(self, n):
a, b = 1, 1
for _ in range(n - 1):
a, b = b, a + b
return bπ― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated