Number of Ways to Reach a Position After Exactly k Steps - Problem
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: The number line includes negative integers.
Input & Output
Example 1 — Basic Movement
$
Input:
startPos = 1, endPos = 2, k = 3
›
Output:
3
💡 Note:
3 ways to reach position 2 from position 1 in exactly 3 steps: RLL (1→2→1→0→1→2), LRL (1→0→1→2), LLR (1→0→-1→0→1→2). Wait, let me recalculate: RLL: 1→2→1→0, LRL: 1→0→1→2, LLR: 1→0→-1→0. Actually the 3 ways are: RLR: 1→2→1→2, LRR: 1→0→1→2, RRL: this doesn't work. Let me recalculate properly: We need exactly 3 steps to go from 1 to 2 (distance 1). Ways: RLR (1→2→1→2), LRR (1→0→1→2), RLL then R won't work in 3 steps. The correct 3 ways are: RLR, LRR, and RRL doesn't work. Actually: RLR, LRR, LRL all reach position 2 in 3 steps.
Example 2 — Same Position
$
Input:
startPos = 2, endPos = 2, k = 2
›
Output:
2
💡 Note:
2 ways to stay at position 2 in exactly 2 steps: RL (2→3→2) or LR (2→1→2). Both sequences return to the starting position.
Example 3 — Impossible Case
$
Input:
startPos = 1, endPos = 3, k = 1
›
Output:
0
💡 Note:
Impossible to reach position 3 from position 1 in exactly 1 step, since the distance is 2 but we can only move 1 step total.
Constraints
- 1 ≤ startPos, endPos ≤ 1000
- 1 ≤ k ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Start at position 1, want to reach 2 in 3 steps
2
Process
Try different combinations of L and R moves
3
Output
Count valid sequences that use exactly k steps
Key Takeaway
🎯 Key Insight: Transform the path-counting problem into a combinatorial problem of choosing which steps go right vs left
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code