The "Sliding Puzzle" interview question is a classic state-space search problem. You are given a 2x3 board with numbers 1 through 5 and one empty space (represented by 0). The goal is to find the minimum number of moves to reach the target state [[1,2,3],[4,5,0]]. A move consists of swapping the 0 with an adjacent number (up, down, left, right). This "Sliding Puzzle coding problem" is a variation of the famous 8-puzzle but on a smaller grid.
Companies like Uber and Google ask this because it tests a candidate's ability to model a problem as a graph. Each board configuration is a "state" (a node in the graph), and a move is an "edge" between states. It evaluates your proficiency with Breadth-First Search (BFS) for finding the shortest path in an unweighted graph and your ability to manage visited states using memoization or hash sets.
The primary pattern is "Breadth-First Search (BFS) interview pattern". Since we want the minimum number of moves, BFS is the ideal choice.
(current_state, moves_count).visited set to keep track of seen configurations to avoid infinite loops.Initial board: [[4,1,2],[5,0,3]] -> String "412503"
A common error is not correctly mapping the 2D grid indices to the 1D string indices, especially for "up" and "down" moves. Another mistake is forgetting to use a visited set, which leads to redundant work and potential stack overflow or memory exhaustion. Some candidates might try Depth-First Search (DFS), but DFS does not guarantee the shortest path and is much harder to implement for this specific requirement.
When you need the "shortest path" or "minimum moves" in a graph where all edges have a weight of 1, always reach for BFS. Practice converting 2D grids into strings or integers to simplify the state representation. This technique is useful in many "Sliding Puzzle interview question" variations and pathfinding problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Length of Longest V-Shaped Diagonal Segment | Hard | Solve | |
| Minimum Moves to Spread Stones Over Grid | Medium | Solve | |
| 01 Matrix | Medium | Solve | |
| As Far from Land as Possible | Medium | Solve | |
| Number of Ways of Cutting a Pizza | Hard | Solve |