Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2400: Number of Ways to Reach a Position After Exactly k Steps

LeetCode 2400 Solution Explanation

Explanation:

To solve this problem, we can use dynamic programming to keep track of the number of ways to reach a certain position after a certain number of steps. We can create a 2D array dp where dp[i][j] represents the number of ways to reach position i after j steps. We can fill up this array iteratively based on the following recurrence relation:

dp[i][j] = dp[i-1][j-1] + dp[i+1][j-1]

This means that the number of ways to reach position i after j steps is the sum of the number of ways to reach position i-1 and i+1 after j-1 steps.

We need to handle the boundary conditions carefully, as we can only move left or right by one step at each move.

The final answer will be the value at endPos in the dp array after k steps.

Time Complexity:

The time complexity of this solution is O(k * endPos) where k is the number of steps and endPos is the end position.

Space Complexity:

The space complexity of this solution is O(k * endPos) for the 2D array dp.

:

LeetCode 2400 Solutions in Java, C++, Python

class Solution {
    public int numWays(int startPos, int endPos, int k) {
        int MOD = 1000000007;
        int maxPos = Math.max(Math.abs(startPos), Math.abs(endPos));
        int[][] dp = new int[2 * maxPos + 1][k + 1];
        dp[startPos + maxPos][0] = 1;

        for (int j = 1; j <= k; j++) {
            for (int i = 0; i < dp.length; i++) {
                dp[i][j] = ((i > 0 ? dp[i - 1][j - 1] : 0) + (i < dp.length - 1 ? dp[i + 1][j - 1] : 0)) % MOD;
            }
        }

        return dp[endPos + maxPos][k];
    }
}

Interactive Code Editor for LeetCode 2400

Improve Your LeetCode 2400 Solution

Use the editor below to refine the provided solution for LeetCode 2400. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems