Number of Ways to Stay in the Same Place After Some Steps Problem
Description
LeetCode Problem 1269.
You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
Example 2:
Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
Example 3:
Input: steps = 4, arrLen = 2
Output: 8
Constraints:
1 <= steps <= 5001 <= arrLen <= 10^6
Solution
Approach: Memoized Search
Let dfs(i, j) be the number of ways to end at index 0 when the pointer is at index i and j steps are left. Each step goes left, stays or goes right, so
dfs(i, j) = dfs(i - 1, j - 1) + dfs(i, j - 1) + dfs(i + 1, j - 1),
with dfs(0, 0) = 1, and 0 whenever i falls outside the array. The answer is dfs(0, steps), taken modulo 10^9 + 7 at every addition.
arrLen can be 10^6, far too many positions for a table. The key observation is that if i > j, the pointer cannot walk back to 0 in the j steps left, so the result is 0. Starting from dfs(0, steps) the pointer is then never further than steps / 2 from index 0, so only O(steps2) states are ever reached, whatever arrLen is. A memo table of size (steps + 1) x (steps + 1) caches them, so each state is computed once.
Complexity: O(steps2) time and space. The recursion is at most steps levels deep.
from functools import lru_cache
class Solution:
def numWays(self, steps: int, arrLen: int) -> int:
MOD = 10**9 + 7
@lru_cache(None)
def dfs(i: int, j: int) -> int:
# ways to end at index 0 from index i with j steps left
if i < 0 or i >= arrLen or i > j:
return 0 # off the array, or too far to walk back in time
if j == 0:
return 1 # here i == 0
return (dfs(i - 1, j - 1) + dfs(i, j - 1) + dfs(i + 1, j - 1)) % MOD
return dfs(0, steps)