Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1269: Number of Ways to Stay in the Same Place After Some Steps

In this guide, we solve Leetcode #1269 Number of Ways to Stay in the Same Place After Some Steps in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

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

Python Solution

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

The time complexity is O(steps×steps)O(steps \times steps)O(steps×steps), and the space complexity is O(steps×steps)O(steps \times steps)O(steps×steps). The space complexity is O(steps×steps)O(steps \times steps)O(steps×steps).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy