Skip to main content

Find Number of Ways to Reach the K-th Stair - Solution & Explanation

Practice this problem

Problem Statement

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 + 2jump. And then, jump becomes jump + 1.

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

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

 

Example 1:

Input: k = 0

Output: 2

Explanation:

The 2 possible ways of reaching stair 0 are:

  • Alice starts at stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
  • Alice starts at stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.

Example 2:

Input: k = 1

Output: 4

Explanation:

The 4 possible ways of reaching stair 1 are:

  • Alice starts at stair 1. Alice is at stair 1.
  • Alice starts at stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
  • Alice starts at stair 1.
    • Using an operation of the second type, she goes up 20 stairs to reach stair 2.
    • Using an operation of the first type, she goes down 1 stair to reach stair 1.
  • Alice starts at stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • Using an operation of the second type, she goes up 20 stairs to reach stair 1.
    • Using an operation of the first type, she goes down 1 stair to reach stair 0.
    • Using an operation of the second type, she goes up 21 stairs to reach stair 2.
    • Using an operation of the first type, she goes down 1 stair to reach stair 1.

 

Constraints:

  • 0 <= k <= 109

Approach Overview

Problem Overview: You start from stair 1 and perform a sequence of constrained moves to reach stair k. The challenge is counting how many valid sequences of operations end exactly at k. Because moves grow exponentially and have restrictions on consecutive steps, the solution relies on math, combinatorics, and efficient state checks rather than brute‑force enumeration.

Approach 1: Sorting and Two-Pointer Technique (Time: O(n log n), Space: O(1) or O(n))

Generate all candidate stair positions that can appear during valid sequences. These positions come from applying the allowed jump pattern and optional step-backs. Once you have the candidate values, sort them and use the two‑pointer technique to count combinations that end exactly at k. One pointer starts from the smallest reachable state while the other scans from the largest; adjust pointers based on whether the current sum or transformation overshoots or undershoots k. Sorting costs O(n log n), while the two‑pointer scan runs in O(n). This method is useful when the candidate states are precomputed and you want a deterministic scan without extra memory overhead.

Approach 2: HashSet for Complement Check (Time: O(n), Space: O(n))

Instead of sorting, store generated stair states in a HashSet. For each state, compute the complement or transformation needed to reach k. A constant‑time hash lookup checks whether the complementary state exists. This reduces the search phase to linear time, giving O(n) complexity after generating the candidate states. The trade‑off is additional memory usage for the hash structure. Hash‑based lookups work well when the number of candidate states grows and sorting would become the bottleneck.

Both strategies rely on understanding how the allowed moves produce valid stair numbers. That reasoning often comes from dynamic programming or direct mathematical observation of the jump pattern. Once the reachable states are known, the problem becomes an efficient counting task.

Recommended for interviews: Interviewers typically expect a math‑driven observation that reduces the search space first. After identifying the reachable stair states, a linear solution using a hash structure is usually preferred because it achieves O(n) lookup time and demonstrates familiarity with efficient counting techniques. Discussing the sorted two‑pointer method first can still help show problem‑solving progression before presenting the optimal hash‑based approach.

Approach 1: Approach 1: Sorting and Two-Pointer Technique

This approach involves sorting the array and using two pointers to find the solution. Once sorted, two pointers can be used to iterate through the array and check for the required condition. This method reduces time complexity by effectively narrowing down potential solutions through the sorted order.

The code sorts an array and uses two pointers to find pairs of numbers that sum up to a target value. The sort function arranges the array in ascending order. The findPairs function uses two indices, left and right, to iterate from the beginning and end of the sorted array, respectively. It checks sum of the elements and adjusts the pointers until the desired pair is found.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) due to nested loops in the sorting algorithm.
Space Complexity: O(1) as no additional storage apart from input data.

Try this approach in the editor →

Approach 2: Approach 2: HashSet for Complement Check

This approach uses a HashSet to keep track of the elements already visited. For each element in the array, we calculate the complement that would sum up to the target value. If the complement is found in the HashSet, a pair is identified. This technique leverages the efficiency of hash table lookups to optimize the search process.

This C code uses a simple hash table implemented with separate chaining (linked lists) to store array elements. For each element, it checks if the complement needed to reach the target exists in the table. This allows pair finding in average double for O(1) time for lookup.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) average, O(n^2) worst-case
Space Complexity: O(n) for the hash table.

Try this approach in the editor →

Approach 3: Memoization Search

We design a function dfs(i, j, jump), which represents the number of ways to reach the kth step when currently at the ith step, having performed j operation 1's and jump operation 2's. The answer is dfs(1, 0, 0).

The calculation process of the function dfs(i, j, jump) is as follows:

  • If i > k + 1, since we cannot go down twice in a row, we cannot reach the kth step again, so return 0;
  • If i = k, it means that we have reached the kth step. The answer is initialized to 1, and then continue to calculate;
  • If i > 0 and j = 0, it means that we can go down, recursively calculate dfs(i - 1, 1, jump);
  • Recursively calculate dfs(i + 2^{jump}, 0, jump + 1), and add it to the answer.

To avoid repeated calculations, we use memoization search to save the calculated states.

The time complexity is O(log^2 k), and the space complexity is O(log^2 k).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Sorting and Two-Pointer Technique

Time Complexity: O(n^2) due to nested loops in the sorting algorithm.
Space Complexity: O(1) as no additional storage apart from input data.

Approach 2: HashSet for Complement Check

Time Complexity: O(n) average, O(n^2) worst-case
Space Complexity: O(n) for the hash table.

Memoization Search

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sorting + Two-Pointer TechniqueO(n log n)O(1)–O(n)When candidate states can be sorted and scanned deterministically with minimal extra memory
HashSet for Complement CheckO(n)O(n)Best for fast lookups when checking if a complementary state exists

Video Solution

Find Number of Ways to Reach the K-th Stair | Recursion+Memo | Leetcode 3154 | codestorywithMIKcodestorywithMIK4,180 views views

Watch 6 more video solutions →

Frequently Asked Questions

Is Find Number of Ways to Reach the K-th Stair easy or hard?
This problem is classified as Hard because the main difficulty lies in recognizing the mathematical structure of the moves and reducing the exponential search space. Efficient solutions combine combinatorics with optimized lookup strategies.
Find Number of Ways to Reach the K-th Stair Python/Java solution
Typical implementations generate candidate states and then use either a sorted two-pointer scan or a HashSet lookup to count valid ways. The logic is straightforward to implement in Python, Java, C++, or JavaScript because it mainly relies on iteration and hash-based membership checks.
How to solve Find Number of Ways to Reach the K-th Stair in O(n)?
First compute the reachable stair states based on the allowed jump operations. Store these states in a HashSet and iterate through them while checking if the complementary state needed to reach k exists. Hash lookups run in O(1), resulting in an overall O(n) algorithm.
What is the best approach for Find Number of Ways to Reach the K-th Stair?
The most efficient approach is to derive the possible stair states using mathematical reasoning and then count valid combinations using a HashSet. This allows constant-time lookups for complementary states and reduces the overall complexity to O(n) time with O(n) space.
Is Find Number of Ways to Reach the K-th Stair asked at Google/Amazon/Meta?
Hard combinatorics and state‑transition problems like this commonly appear in interviews at companies such as Google, Amazon, and Meta. They test mathematical reasoning, efficient state counting, and the ability to optimize brute‑force approaches.
What data structure is used in Find Number of Ways to Reach the K-th Stair?
Common implementations use arrays or lists to store generated states and a HashSet for fast membership checks. Some optimized discussions also reference dynamic programming or combinatorics to reduce the search space.
What is the time complexity of Find Number of Ways to Reach the K-th Stair?
The optimized solution runs in O(n) time when using a HashSet for complement checks after generating candidate states. A sorting-based approach followed by a two-pointer scan requires O(n log n) time due to the sorting step.

Ready to solve this problem?

Practice Find Number of Ways to Reach the K-th Stair with our built-in code editor and test cases.

Practice on FleetCode