Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2400: Number of Ways to Reach a Position After Exactly k Steps

In this guide, we solve Leetcode #2400 Number of Ways to Reach a Position After Exactly k Steps in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Math, Dynamic Programming, Combinatorics

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

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: - 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.

Python Solution

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

The time complexity is O(k2)O(k^2)O(k2), and the space complexity is O(k2)O(k^2)O(k2). The space complexity is O(k2)O(k^2)O(k2).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy