Number of Ways to Stay in the Same Place After Some Steps - Problem

Imagine you have a pointer starting at position 0 in an array of size arrLen. At each step, you can make one of three moves:

  • Move left (decrease position by 1)
  • Move right (increase position by 1)
  • Stay in the same position

Important: The pointer must never go outside the array bounds (positions 0 to arrLen-1).

Given steps total moves and array length arrLen, find the number of ways to end up back at position 0 after exactly steps moves.

Since the answer can be very large, return it modulo 109 + 7.

Example: With steps = 3 and arrLen = 2, you could go: stay→stay→stay, or right→left→stay, etc.

Input & Output

example_1.py — Basic case
$ Input: steps = 3, arrLen = 2
Output: 4
💡 Note: There are 4 different ways: 1) Stay-Stay-Stay, 2) Stay-Right-Left, 3) Right-Left-Stay, 4) Right-Stay-Left. All paths return to position 0 after exactly 3 steps.
example_2.py — Single position
$ Input: steps = 2, arrLen = 1
Output: 1
💡 Note: With array length 1, we can only stay at position 0. There's only one way: Stay-Stay.
example_3.py — Large steps
$ Input: steps = 4, arrLen = 2
Output: 8
💡 Note: Multiple combinations including: Stay-Stay-Stay-Stay, Right-Left-Stay-Stay, Stay-Right-Left-Stay, etc. All must end at position 0.

Visualization

Tap to expand
Robot Bridge Journey🤖Position 0Position 1Position 2StayRightLeftKey Insight• Robot can't go beyondsteps distance from start• Use DP to count paths• Space optimize withonly 2 arraysTime: O(steps × min(steps, n))
Understanding the Visualization
1
Starting Position
Robot starts at position 0 on the bridge
2
Available Moves
Each step: stay, move left, or move right (within bounds)
3
Build DP Table
Track ways to reach each position with each number of steps
4
Space Optimization
Only keep current and previous step data to save memory
Key Takeaway
🎯 Key Insight: We can optimize both time and space by recognizing that positions beyond 'steps' distance are unreachable, and we only need to store the previous step's results to compute the current step.

Time & Space Complexity

Time Complexity
⏱️
O(steps × min(steps, arrLen))

We iterate through each step and for each step, we process positions up to min(steps, arrLen) since we can't go further than steps distance from origin

n
2n
Linear Growth
Space Complexity
O(min(steps, arrLen))

We only store current and previous DP arrays, each of size min(steps, arrLen)

n
2n
Linearithmic Space

Constraints

  • 1 ≤ steps ≤ 500
  • 1 ≤ arrLen ≤ 106
  • Answer fits in 32-bit integer after modulo operation
Asked in
Google 42 Amazon 38 Microsoft 31 Meta 25
28.8K Views
Medium-High Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen