




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))
1#include <iostream>
2#include <vector>
3#define MOD 1000000007
4using namespace std;
5
6int numWays(int steps, int arrLen) {
7    int maxPos = min(steps, arrLen - 1);
8    vector<vector<int>> dp(steps + 1, vector<int>(maxPos + 1, 0));
9    dp[0][0] = 1;
10    for (int i = 1; i <= steps; ++i) {
11        for (int j = 0; j <= maxPos; ++j) {
12            dp[i][j] = dp[i - 1][j];
13            if (j > 0) dp[i][j] = (dp[i][j] + dp[i - 1][j - 1]) % MOD;
14            if (j < maxPos) dp[i][j] = (dp[i][j] + dp[i - 1][j + 1]) % MOD;
15        }
16    }
17    return dp[steps][0];
18}
19
20int main() {
21    cout << numWays(3, 2) << endl; // Output: 4
22    return 0;
23}This C++ solution uses the same logic as the C solution, implementing the dynamic programming approach with a STL vector for ease of use and dynamic sizing.
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))
This C implementation uses recursion with memoization. The recursive function explores all directions (stay, left, right) and stores results in a cache to prevent redundant computation, ensuring efficiency.