




Sponsored
Sponsored
This approach leverages dynamic programming to find the number of ways to stay at index 0 after a given number of steps. We define a 2D table dp[i][j] where i represents the number of steps remaining, and j represents the current position of the pointer.
To optimize computation, we can limit the table size to the minimum of steps and arrLen since going beyond these positions is unnecessary.
Time Complexity: O(steps * min(steps, arrLen))
Space Complexity: O(steps * min(steps, arrLen))
1using System;
2
3class NumWays
4{
5    const int MOD = 1000000007;
6    public int NumWays(int steps, int arrLen)
7    {
8        int maxPos = Math.Min(steps, arrLen - 1);
9        int[,] dp = new int[steps + 1, maxPos + 1];
10        dp[0, 0] = 1;
11        for (int i = 1; i <= steps; i++)
12        {
13            for (int j = 0; j <= maxPos; j++)
14            {
                dp[i, j] = dp[i - 1, j];
                if (j > 0) dp[i, j] = (dp[i, j] + dp[i - 1, j - 1]) % MOD;
                if (j < maxPos) dp[i, j] = (dp[i, j] + dp[i - 1, j + 1]) % MOD;
            }
        }
        return dp[steps, 0];
    }
    static void Main(string[] args)
    {
        NumWays nw = new NumWays();
        Console.WriteLine(nw.NumWays(3, 2)); // Output: 4
    }
}This C# solution builds on the same dynamic programming approach. The transition states manage the potential moves while maintaining accuracy and efficiency using the Math.Min function to limit the table size.
This approach utilizes recursion combined with memoization to optimize the recursive calls. Here, recursion is used to explore all possible paths dynamically adjusting by staying at, moving left, or moving right from each position in every step.
The results of the recursive calls are stored in a memoization table to avoid redundant calculations.
Time Complexity: O(steps * min(steps, arrLen))
Space Complexity: O(steps * min(steps, arrLen))
In JavaScript, recursion is paired with memoization to store intermediate results, enhancing efficiency by eliminating unnecessary recalculations during recursive state transitions.