Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the probability it is still on the board?
Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the probability it is still on the board?
def prob(n, k, r, c):
moves = [(1,2),(2,1),(-1,2),(-2,1),(1,-2),(2,-1),(-1,-2),(-2,-1)]
dp = [[0.0] * n for _ in range(n)]; dp[r][c] = 1.0
for _ in range(k):
nd = [[0.0] * n for _ in range(n)]
for x in range(n):
for y in range(n):
if dp[x][y]:
for dx, dy in moves:
if 0 <= x + dx < n and 0 <= y + dy < n:
nd[x+dx][y+dy] += dp[x][y] / 8
dp = nd
return sum(map(sum, dp))
print(f"{prob(4, 2, 1, 1):.4f}")What is printed?- A. 0.2500
- B. 0.1875
- C. 0.1562
- D. 0.5000
Correct answer: C. 0.1562
From (1, 1) on a 4 × 4 board 4 of 8 moves stay on: (0, 3), (2, 3), (3, 0), (3, 2). From (2, 3) and (3, 2) three moves stay on, from (0, 3) and (3, 0) only two, so P = (3 + 3 + 2 + 2)/64 = 0.15625, printed as 0.1562.
More Coding Interview Problems questions
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…
- Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times. python…
- Problem: AND of every integer in the range [lo, hi]. python def rangeand(lo, hi): shift = 0 while lo != hi: lo >>= 1; hi >>= 1; shift += 1…
- Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers. python def ugly(n): u =…