LeetCode 3154: Find Number of Ways to Reach the K-th Stair Solution

Master LeetCode problem 3154 (Find Number of Ways to Reach the K-th Stair), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3154. Find Number of Ways to Reach the K-th Stair

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming to keep track of the number of ways to reach each stair up to k. We can define a dp array where dp[i] represents the number of ways to reach stair i.

At each step, we can either go down to i-1 or go up to i+2*jump. We need to consider both cases and update the dp array accordingly.

The base cases are dp[0] = 1 and dp[1] = 1, as we can reach stair 0 from stair 1 in one way, and we are already at stair 1 initially.

The time complexity of this approach is O(k) as we iterate through all stairs up to k, and the space complexity is also O(k) to store the dp array.

:

Solution Code

class Solution {
    public int numWays(int k) {
        int[] dp = new int[k + 1];
        dp[0] = 1;
        dp[1] = 1;
        
        for (int i = 2; i <= k; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        
        return dp[k];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3154 (Find Number of Ways to Reach the K-th Stair)?

This page provides optimized solutions for LeetCode problem 3154 (Find Number of Ways to Reach the K-th Stair) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3154 (Find Number of Ways to Reach the K-th Stair)?

The time complexity for LeetCode 3154 (Find Number of Ways to Reach the K-th Stair) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3154 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3154 in Java, C++, or Python.

Back to LeetCode Solutions