Solve a Two-by-Three Sliding Tile Puzzle in the Fewest Moves
Last updated: November 29, 2026
Quick Overview
A 2 by 3 board holds tiles 1 to 5 and one empty square 0. A move slides a tile adjacent to 0 into the empty square. Return the minimum moves to reach [[1,2,3],[4,5,0]], or -1 if impossible.
0
0
0 solved
A 2 by 3 board holds tiles 1 to 5 and one empty square 0. A move slides a tile adjacent to 0 into the empty square. Return the minimum moves to reach [[1,2,3],[4,5,0]], or -1 if impossible.
An onsite question on state-space BFS where each node is a whole board. Google interviewers use it to see if you encode states compactly, precompute neighbor moves, and can explain the parity argument for why half of all boards are unsolvable.
What the Interviewer Expects
- Encode each board as a string or tuple
- Precompute which indices are adjacent to each position
- Run BFS from the start state
- Explain the 360-state bound for a 2 by 3 board
- Mention parity of inversions for solvability
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Prove which boards are unsolvable using inversion parity.
- Scale this to the 3 by 3 or 4 by 4 puzzle; what search do you use?
- Design an admissible heuristic for A*.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: 2 by 3 list with values 0..5.
- Move: swap 0 with an orthogonal neighbor.
- Output: minimum moves to the solved board or -1....
High-Level Design
Flatten the board into a 6-character string, index r * 3 + c. Precompute, for each position of the 0, the positions it can swap with: position 0 neighbors 1 and 3, position 1 neighbors 0, 2, 4, and ...