Number of Ways to Stay in the Same Place After Some Steps - 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).

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.

Input & Output

Example 1 — Basic Case
$ Input: steps = 3, arrLen = 2
Output: 4
💡 Note: 4 ways to stay at index 0 after 3 steps: Stay→Stay→Stay, Stay→Right→Left, Right→Stay→Left, Right→Left→Stay
Example 2 — Single Position
$ Input: steps = 2, arrLen = 1
Output: 1
💡 Note: Only one position available, so must stay at index 0. Only way: Stay→Stay
Example 3 — Larger Array
$ Input: steps = 4, arrLen = 3
Output: 8
💡 Note: Multiple paths possible with more positions and steps available

Constraints

  • 1 ≤ steps ≤ 500
  • 1 ≤ arrLen ≤ 106
  • The answer is guaranteed to fit in a 32-bit integer

Visualization

Tap to expand
INPUTALGORITHMRESULTsteps = 3, arrLen = 201Array positionsPStart at position 0Need to return hereafter exactly 3 steps1Build DP Table2dp[i][j] = ways at pos j after i steps3Base: dp[0][0] = 14Fill: sum from adjacent positionsDP Table:Step 0: [1, 0]Step 1: [1, 1]Step 2: [2, 1]Step 3: [3, 2]Answer: dp[3][0] = 344 different waysto return to position 0after exactly 3 steps:Stay→Stay→StayStay→Right→LeftRight→Stay→LeftRight→Left→StayKey Insight:Track (position, remaining_steps) pairs with DP to avoid redundant calculationsTutorialsPoint - Number of Ways to Stay in Same Place | Space-Optimized DP
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.0K Views
Medium Frequency
~25 min Avg. Time
892 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