#3154
Find Number of Ways to Reach the K-th Stair
HardMathDynamic ProgrammingBit ManipulationMemoizationCombinatoricsDynamic ProgrammingCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses combinatorial mathematics to calculate the number of ways to reach stair k based on the number of jumps and downward moves. It leverages the fact that the position can be expressed as a function of jumps and downs.
⚙️
Algorithm
3 steps- 1Step 1: For each valid number of jumps x, calculate the maximum number of downs y that can be performed.
- 2Step 2: Use the formula 2^x to determine the number of ways to arrange x jumps and y downs.
- 3Step 3: Sum the results for all possible x values until the stair k is reached.
solution.py12 lines
1def countWays(k):
2 if k == 0:
3 return 2
4 total_ways = 0
5 for x in range(k + 1):
6 y = k - (2 ** x)
7 if y >= 0 and y % 2 == 0:
8 total_ways += 2 ** x
9 return total_ways
10
11# Example usage
12print(countWays(1)) # Output: 4ℹ
Complexity note: The time complexity is O(n) because we iterate through possible jump values up to k, and the space complexity is O(1) since we only use a few variables.
- 1Understanding the relationship between jumps and downs is crucial.
- 2Recognizing that the problem can be framed in terms of combinatorial arrangements helps simplify the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.