Skip to main content
Back to problems
#1269
Hard Algorithms

Number of ways to stay in the same place after some steps

Dynamic Programming
50.0% acceptance
Feb 25, 2026
1597
67
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 109 + 7.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn num_ways(steps: i32, arr_len: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let steps = steps as usize;
    // Max position we can ever be is min(steps/2, arr_len-1)
    let max_pos = (steps / 2).min((arr_len - 1) as usize);

    // dp[j] = ways to be at position j after i steps
    let mut dp = vec![0i64; max_pos + 1];
    dp[0] = 1;

    for _ in 0..steps {
      let mut ndp = vec![0i64; max_pos + 1];
      for j in 0..=max_pos {
        if dp[j] == 0 { continue; }
        // Stay
        ndp[j] = (ndp[j] + dp[j]) % MOD;
        // Move right
        if j + 1 <= max_pos {
          ndp[j + 1] = (ndp[j + 1] + dp[j]) % MOD;
        }
        // Move left
        if j > 0 {
          ndp[j - 1] = (ndp[j - 1] + dp[j]) % MOD;
        }
      }
      dp = ndp;
    }
    dp[0] as i32
  }
}