Number of Ways to Stay in the Same Place After Some Steps — LeetCode 1269 Python Solution

HardDynamic Programming
Problem
#1269
Reading time
3 min

The problem

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).

Example

Input
steps = 3, arrLen = 2
Output
4
Explanation
There are 4 differents ways to stay at index 0 after 3 steps.

Python solution

Python
class Solution:
    def numWays(self, steps: int, arrLen: int) -> int:
        @cache
        def dfs(i, j):
            if i > j or i >= arrLen or i < 0 or j < 0:
                return 0
            if i == 0 and j == 0:
                return 1
            ans = 0
            for k in range(-1, 2):
                ans += dfs(i + k, j - 1)
                ans %= mod
            return ans

        mod = 10**9 + 7
        return dfs(0, steps)

Complexity

MeasureComplexity
TimeO(steps \times steps)
SpaceO(steps \times steps) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps?
LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps is rated Hard on LeetCode.
What is the time complexity of LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps?
The Python solution on this page runs in O(steps \times steps).
What is the space complexity of LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps?
The Python solution on this page uses O(steps \times steps) auxiliary space.
What topics does LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps cover?
LeetCode 1269. Number of Ways to Stay in the Same Place After Some Steps is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview