← Microsoft Interview Insights
I jumped straight to BFS which was right, but encoding the board state tripped me up for a few minutes.
Model the puzzle as a state-space search problem where each state is a permutation of the 16 positions. Use BFS to explore moves level by level, tracking visited states to avoid cycles, and return the depth when the goal state is reached. Before searching, check solvability using the inversion parity rule to quickly return -1 for unsolvable configurations.
Pro tip: Mention that BFS is optimal for unweighted moves but can be memory-intensive; for a 4x4 puzzle, bidirectional BFS or A* with Manhattan distance heuristic would be more efficient in practice. Also, precompute solvability to avoid unnecessary search.
Encode the board as a string or tuple of 16 characters (e.g., '123456789ABCDEF0' with '0' for blank) to enable hashing and fast comparison.
Count inversions (ignoring blank) and use the parity rule: for a 4x4 board, the puzzle is solvable if the number of inversions plus the row of the blank from the bottom is even.
Use a queue for BFS, starting with the initial state at depth 0. Maintain a visited set to avoid revisiting states.
For each state, generate all valid moves by swapping the blank with adjacent tiles. If a neighbor is the goal, return depth+1; else if unvisited, add to queue and visited set.
If the queue empties without reaching the goal, return -1. (Alternatively, return -1 immediately after solvability check fails.)
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.