Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
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 states.
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 states.
from collections import deque
def reachable(start):
nb = {0: (1, 2), 1: (0, 3), 2: (0, 3), 3: (1, 2)}
seen, q = {start}, deque([start])
while q:
s = q.popleft(); z = s.index('0')
for j in nb[z]:
t = list(s); t[z], t[j] = t[j], t[z]; t = ''.join(t)
if t not in seen: seen.add(t); q.append(t)
return len(seen)
print(reachable("1230"), reachable("2130"))What is printed?- A. 12 12
- B. 24 24
- C. 12 24
- D. 4 4
Correct answer: A. 12 12
Each state is a node; sliding the blank to a neighbour is an edge. Of the 4! = 24 arrangements of a 2 × 2 board, only half are reachable from any start (permutation parity is invariant once the blank's position is accounted for), giving two components of 12 states. BFS over states is O(states × moves).
More Coding Interview Problems questions
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…
- Problem: Find the minimum effort path in a grid where effort is the maximum absolute height difference between consecutive cells. python…
- Problem: Return the number of steps to reach the exit of a maze grid ('.' open, '+' wall) from an entrance, where an exit is an open…