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

You are given a non-negative integer k. There exists a staircase with an infinite number of stairs, with the lowest stair numbered 0.

Alice has an integer jump, with an initial value of 0. She starts on stair 1 and wants to reach stair k using any number of operations.

If she is on stair i, in one operation she can:

  • Go down to stair i - 1. This operation cannot be used consecutively or on stair 0.
  • Go up to stair i + 2^jump. And then, jump becomes jump + 1.

Return the total number of ways Alice can reach stair k.

Note: It is possible that Alice reaches stair k, and performs some operations to reach stair k again.

Input & Output

Example 1 — Basic Case
$ Input: k = 1
Output: 2
💡 Note: Alice starts at stair 1 (already at target). She can also go up to 2 then down to 1. Two ways total.
Example 2 — Multiple Paths
$ Input: k = 2
Output: 2
💡 Note: Path 1: Start at 1, go up by 2^0=1 to reach 2. Path 2: Start at 1, go up by 2^0=1 to 2, up by 2^1=2 to 4, down to 3, down to 2.
Example 3 — Edge Case
$ Input: k = 0
Output: 1
💡 Note: Alice starts at 1, can only go down to 0 (one way since she cannot go down consecutively).

Constraints

  • 0 ≤ k ≤ 109

Visualization

Tap to expand
Find Number of Ways to Reach K-th Stair INPUT 0 1 (k) 2 3 4 A Start Parameters k = 1 (target stair) start = stair 1 jump = 0 (initial) ALGORITHM STEPS 1 Operations DOWN: i-1 (not consecutive) UP: i + 2^jump, jump++ 2 Way 1: Stay at k=1 Start at 1, do nothing Already at target! 3 Way 2: Up then Down UP: 1 + 2^0 = 2 DOWN: 2 - 1 = 1 (k) 4 Count Valid Paths Use recursion/memoization Track state: (stair, jump) (1,0) (2,1) (1,1) FINAL RESULT Path 1 Stay at stair 1 1 --[stay]--> 1 Path 2 Go up, then down 1 --> 2 --> 1 OUTPUT 2 Total ways = 2 [OK] Verified Key Insight: The problem uses dynamic programming with state (current_stair, jump_power, can_go_down). Each UP operation doubles the jump distance (2^jump), making exploration exponential but bounded. TutorialsPoint - Find Number of Ways to Reach the K-th Stair | Optimal Solution
Asked in
Google 15 Meta 12 Apple 8
7.3K Views
Medium Frequency
~35 min Avg. Time
189 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