Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS).
Problem: Find the minimum number of jumps for a knight to reach a target on an infinite board (BFS).
from collections import deque
def knight(tx, ty):
tx, ty = abs(tx), abs(ty)
moves = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
q, seen = deque([(0, 0, 0)]), {(0, 0)}
while q:
x, y, d = q.popleft()
if (x, y) == (tx, ty): return d
for dx, dy in moves:
nx, ny = x + dx, y + dy
if -2 <= nx <= tx + 2 and -2 <= ny <= ty + 2 and (nx, ny) not in seen:
seen.add((nx, ny)); q.append((nx, ny, d + 1))
print(knight(1, 1), knight(5, 5), knight(0, 1))What is printed?- A. 2 4 3
- B. 2 4 1
- C. 4 4 3
- D. 2 5 3
Correct answer: A. 2 4 3
BFS on board squares; symmetry lets us fold the target into the first quadrant, and a small margin (−2) is enough because optimal paths never wander far. (1, 1) needs 2 moves, e.g. (2, −1) then (−1, 2); the adjacent square (0, 1) surprisingly needs 3; (5, 5) needs 4. Without the margin, targets like (1, 1) would be unreachable inside the box. O(area) of the bounded box.
More Coding Interview Problems questions
- Problem: Count the inversions of an array with merge sort. python def inv(a): if len(a) < 2: return a, 0 m = len(a) // 2 L, x =…
- Problem: Return the maximum sum of a subarray of size exactly k, and the sum of the best circular subarray (wrapping allowed). python def…
- Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed). cpp int n = 8; vector<long long> t(n + 1, 0); void…
- Problem: Range minimum queries with a sparse table after O(n log n) preprocessing. python a = [7, 2, 9, 4, 3, 8, 6, 1, 5] n = len(a); LOG…
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…