Skip to main content
Back to problems
#2400
Medium Algorithms

Number of ways to reach a position after exactly k steps

Math Dynamic Programming Combinatorics
36.8% acceptance
Feb 25, 2026
839
68
You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right. Given a positive integer k, return the number of different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it modulo 109 + 7. Two ways are considered different if the order of the steps made is not exactly the same. Note that the number line includes negative integers.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn number_of_ways(start_pos: i32, end_pos: i32, k: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    let diff = (start_pos - end_pos).abs();
    if diff > k || (k - diff) % 2 != 0 { return 0; }
    let r = ((k + diff) / 2) as usize;
    let k = k as usize;
    // C(k, r) mod MOD using Pascal's triangle row
    let mut dp = vec![0i64; k + 1];
    dp[0] = 1;
    for _ in 0..k {
      for j in (1..=k).rev() {
        dp[j] = (dp[j] + dp[j - 1]) % MOD;
      }
    }
    dp[r] as i32
  }
}