Number of Ways to Reach a Position After Exactly k Steps — LeetCode 2400 Python Solution

MediumMathDynamic ProgrammingCombinatorics
Problem
#2400
Reading time
2 min

The problem

You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line.

Example

Input
startPos = 1, endPos = 2, k = 3
Output
3
Explanation
We can reach position 2 from 1 in exactly 3 steps in three ways:

Python solution

Python
class Solution:
    def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:
        @cache
        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)

Complexity

MeasureComplexity
TimeO(k^2)
SpaceO(k^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps?
LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps is rated Medium on LeetCode.
What is the time complexity of LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps?
The Python solution on this page runs in O(k^2).
What is the space complexity of LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps?
The Python solution on this page uses O(k^2) auxiliary space.
What topics does LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps cover?
LeetCode 2400. Number of Ways to Reach a Position After Exactly k Steps is tagged Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview