Find Number of Ways to Reach the K-th Stair - Problem

Imagine Alice on a magical staircase that extends infinitely upward! 🏃‍♀️

Alice starts on stair 1 and wants to reach stair k. She has a special jump power that starts at 0 and increases with each upward move.

The Rules:

  • Down Move: From stair i, Alice can go down to stair i - 1 (but not from stair 0, and not twice in a row)
  • Up Move: From stair i, Alice can jump up to stair i + 2^jump, then her jump power increases by 1

Here's the twist: Alice can reach stair k multiple times using different paths! Your task is to count all possible ways she can reach stair k.

Example: If k=1, Alice starts at stair 1 (already there!), but she could also go up and come back down in various ways.

Input & Output

example_1.py — k = 0
$ Input: k = 0
Output: 2
💡 Note: Alice starts at stair 1. She can reach stair 0 by going down once (1 way), or she can jump up to stair 2, then down to stair 1, then down to stair 0 (1 more way). Total: 2 ways.
example_2.py — k = 1
$ Input: k = 1
Output: 4
💡 Note: Alice starts at stair 1 (1 way). She can also: jump to 2 then down to 1 (1 way), jump to 2 then 4 then down to 3 then down to 2 then down to 1 (1 way), and jump to 2 then 4 then down to 3 then down to 2 then jump to 3 then down to 2 then down to 1 (1 way). Total: 4 ways.
example_3.py — k = 2
$ Input: k = 2
Output: 4
💡 Note: Alice can reach stair 2 by: jumping from 1 to 2 (1 way), going down from 1 to 0 then up to 1 then up to 2 (1 way), and other combinations involving multiple jumps and downs. Total: 4 ways.

Visualization

Tap to expand
0START12345ADown(-1)Jump(+2^0=1)After multiple jumps: +2^1, +2^2...Jump Powers: 2^0=1, 2^1=2, 2^2=4, 2^3=8, ...Each up move doubles the jump distance!Alice can reach the same stair multiple times via different paths
Understanding the Visualization
1
Start Position
Alice begins on stair 1 with jump power 0
2
Down Move
Can go down 1 stair (but not consecutively or from stair 0)
3
Up Jump
Jump up 2^jump stairs, then jump power increases by 1
4
Count Paths
Every time Alice reaches stair k, count it as one valid path
Key Takeaway
🎯 Key Insight: The problem has optimal substructure - we can memoize states (position, jump_power, can_go_down) to avoid recalculating the same scenarios multiple times!

Time & Space Complexity

Time Complexity
⏱️
O(log²k)

Limited by the number of reachable states, which is logarithmic in k

n
2n
Linearithmic
Space Complexity
O(log²k)

Memoization cache stores at most O(log²k) unique states

n
2n
Linear Space

Constraints

  • 0 ≤ k ≤ 109
  • Alice starts on stair 1
  • jump starts at 0
  • Cannot go down from stair 0
  • Cannot use down move consecutively
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 24
48.2K Views
Medium Frequency
~25 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen