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?- A. 26
- B. 51
- C. 21
- 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
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…