Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the ways to be back at index 0 after exactly steps steps.

Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the ways to be back at index 0 after exactly `steps` steps.
def ways(steps, n):
    dp = [1] + [0] * (n - 1)
    for _ in range(steps):
        nd = [0] * n
        for i in range(n):
            nd[i] = dp[i] + (dp[i-1] if i else 0) + (dp[i+1] if i + 1 < n else 0)
        dp = nd
    return dp[0]
print(ways(5, 3))
What is printed?
  1. A. 26
  2. B. 51
  3. C. 21
  4. D. 9

Correct answer: C. 21

dp[i] counts ways to be at i; each step sums the three possible predecessors. The positions reachable in 5 steps are limited by the array length 3, which the boundary checks enforce. Result 21, matching enumeration of all 3⁵ move sequences.

More Coding Interview Problems questions

Exams that ask this topic