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?
  1. A. 0.2500
  2. B. 0.1875
  3. C. 0.1562
  4. 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

Exams that ask this topic