Number of Ways to Reach a Position After Exactly k Steps Problem
Description
LeetCode Problem 2400.
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 10^9 + 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.
Example 1:
Input: startPos = 1, endPos = 2, k = 3
Output: 3
Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways:
- 1 -> 2 -> 3 -> 2.
- 1 -> 2 -> 1 -> 2.
- 1 -> 0 -> 1 -> 2.
It can be proven that no other way is possible, so we return 3.
Example 2:
Input: startPos = 2, endPos = 5, k = 10
Output: 0
Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.
Constraints:
1 <= startPos, endPos, k <= 1000
Solution
Approach: Memoized Search
Only the distance to the target matters. Let dfs(i, j) be the number of ways to finish when we are i away from the target with j steps left; the answer is dfs(abs(startPos - endPos), k).
- If
i > jorj < 0, the target is out of reach:0. - If
j = 0, we succeed only wheni = 0:1or0. - Otherwise we step away (
dfs(i + 1, j - 1)) or closer (dfs(abs(i - 1), j - 1)) and add the results modulo10^9 + 7.
A table f[i][j] caches each state so it is computed once.
Complexity: O(k2) time and space.
from functools import lru_cache
class Solution:
def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:
@lru_cache(None)
def dfs(i: int, j: int) -> int:
if i > j or j < 0:
return 0
if j == 0:
return 1 if i == 0 else 0
return (dfs(i + 1, j - 1) + dfs(abs(i - 1), j - 1)) % mod
mod = 10**9 + 7
return dfs(abs(startPos - endPos), k)