← Questions
Sliding puzzle: fewest moves to solve the 15-puzzle
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's coding round, last asked Feb 2026. It tests bfs, a-star and search.
A 4x4 sliding puzzle holds tiles 1 to 15 and one blank (0). A move slides a tile next to the blank into it. Return the fewest moves to reach the solved board, with 1 to 15 in row order and the blank in the bottom-right corner, or -1 if the board cannot be solved.
Interface
Unless you agree on a different interface with the interviewer, assume:
min_moves(board: list[list[int]]) -> int
Example
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]] -> 0
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 0, 15]] -> 1
[[1, 2, 3, 4], [5, 6, 0, 8], [9, 10, 7, 11], [13, 14, 15, 12]] -> 3
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 15, 14, 0]] -> -1 # two tiles swapped
Constraints
- Every value
0..15appears exactly once. - Solvable boards can need up to 80 moves; plain BFS over all reachable states (about 10^13) is impossible.
Clarifying questions
- Do I need the move sequence or just its length?
- Are inputs guaranteed valid (each value once)?
- How hard are the test boards: a few dozen moves, or the worst cases?
- Is there a time limit per board?
What a strong answer covers
- The solvability check before searching: count inversions among the tiles; with a 4-wide board, the board is solvable exactly when inversions plus the blank's row counted from the bottom is odd.
- Why BFS works on the 3x3 version (181,440 states) but not here.
- A* or, better for memory, IDA* with an admissible heuristic: Manhattan distance, improved with linear conflicts or pattern databases.
- Compact state encoding: 16 values of 4 bits in one 64-bit integer, and generating moves by swapping nibbles.
- Avoiding the immediate reverse move in IDA*, and why an admissible heuristic guarantees the optimal answer.
- Tests: solved board, one move away, unsolvable swap.
Follow-ups
- Return the sequence of moves.
- Generalise to an
m x nboard. - Build a 7-8 pattern database and explain why it is admissible.
- Speed up many queries against the same goal.
Where it's asked
- Microsoft · Coding · Last asked Feb 202660 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
