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?
  1. A. 12 12
  2. B. 24 24
  3. C. 12 24
  4. 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

Exams that ask this topic