70. Climbing Stairs
Asked at 33Bloomberg68Amazon67Microsoft66Google63Meta58Apple55Infosys68tcs59Intuit58HPE100HSBC92Adobe89Rakuten88Grammarly88Zoho83Accenture75AMD69Qualcomm68Accolite64Autodesk59Deloitte59Agoda57Cognizant57Media.net57josh technology50Nvidia48BlackRock47Citadel47TikTok46PayPal42Oracle35IBM35Goldman Sachs28
Problem
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?
Example: n = 2 → 2; n = 5 → 8
Constraints: n ≤ 45.
To reach step i you came from i−1 or i−2: ways(i) = ways(i−1) + ways(i−2). Keep two variables.
Complexity: O(n) time, O(1) space.
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 1 # ways(0), ways(1)
for _ in range(n - 1):
a, b = b, a + b
return b
assert Solution().climbStairs(2) == 2
assert Solution().climbStairs(5) == 8
class Solution {
public int climbStairs(int n) {
int a = 1, b = 1;
for (int i = 1; i < n; i++) { int c = a + b; a = b; b = c; }
return b;
}
}
func climbStairs(n int) int {
a, b := 1, 1 // ways(0), ways(1)
for i := 0; i < n-1; i++ {
a, b = b, a+b
}
return b
}