Sliding Puzzle solution explained
Sliding Puzzle is solved with breadth-first search over board states: write the 2 by 3 board as a six-character string, treat every string as a graph node, and connect two strings when one blank swap turns one into the other. The first time BFS pops the solved string, its depth is the fewest moves; if the queue empties first, the answer is -1.
By Evin JohnPublished 8 min read
The problem in plain words
A small tray has two rows of three cells. Five cells hold tiles numbered 1 to 5 and one cell is empty, written as 0. In one move you take a tile that sits directly above, below, left or right of the empty cell and slide it into the gap. The goal arrangement has 1, 2, 3 in the top row and 4, 5, 0 in the bottom row. Return the smallest number of moves that reaches the goal, or -1 if no sequence of moves can.
| Start board | Fewest moves | Why |
|---|---|---|
| [[1,2,3],[4,5,0]] | 0 | Already solved |
| [[1,0,3],[4,2,5]] | 2 | Slide 2 up, then slide 5 left |
| [[2,3,0],[1,4,5]] | 5 | The blank travels left along the top, down, then right along the bottom |
| [[1,3,2],[4,5,0]] | -1 | Two tiles are swapped, and no sequence of slides can fix a single swap |
It helps to flip the point of view. Instead of moving tiles, think of the blank moving. Each move swaps the blank with one of its neighbors, so the number of choices at any moment is two or three, depending on whether the blank sits in a corner or in the middle column.
Turning a board into a graph
The key step in the interview is saying out loud what a node is. Here a node is an entire board, not a cell. Two boards are joined by an edge when one slide changes one into the other. Every edge costs one move, so the shortest path in this unweighted graph is exactly the answer, and BFS finds shortest paths in unweighted graphs.
To store boards in a visited set you need a hashable form. Flatten the grid row by row into a string such as "103425". Position k in the string is row k // 3 and column k % 3. The neighbors of each position never change, so write them down once instead of doing coordinate math in the loop.
| Blank at | Can swap with | Cell |
|---|---|---|
| 0 | 1, 3 | Top left corner |
| 1 | 0, 2, 4 | Top middle |
| 2 | 1, 5 | Top right corner |
| 3 | 0, 4 | Bottom left corner |
| 4 | 1, 3, 5 | Bottom middle |
| 5 | 2, 4 | Bottom right corner |
Slow approach: deepen a DFS one level at a time
A plain DFS can wander forever, so the natural brute force is iterative deepening: try every move sequence of length 0, then 1, then 2, and stop at the first length that reaches the goal. It never keeps a visited set, only the previous blank position so it does not undo its last move. It returns the optimum, but it revisits the same boards many times, and on an unsolvable board it has to exhaust every depth up to its cap before giving up.
def fewest_slides_slow(board):
start = tuple(v for row in board for v in row)
goal = (1, 2, 3, 4, 5, 0)
nb = {0: (1, 3), 1: (0, 2, 4), 2: (1, 5), 3: (0, 4), 4: (1, 3, 5), 5: (2, 4)}
def dls(s, z, depth, prev):
if s == goal: return True
if depth == 0: return False
for j in nb[z]:
if j == prev: continue
l = list(s); l[z], l[j] = l[j], l[z]
if dls(tuple(l), j, depth - 1, z): return True
return False
for d in range(0, 26):
if dls(start, start.index(0), d, -1): return d
return -1Main approach: BFS over board strings
Put the start string in a queue with depth 0 and mark it seen. Pop a board; if it equals "123450", return its depth. Otherwise find the blank, swap it with each neighbor from the table, and push every new string with depth plus one. Because BFS pops boards in order of depth, the first time the goal appears is the minimum. If the queue empties, the goal is in a different part of the state space and the answer is -1.
from collections import deque
def fewest_slides(board):
start = "".join(str(v) for row in board for v in row)
goal = "123450"
neighbors = {0: (1, 3), 1: (0, 2, 4), 2: (1, 5),
3: (0, 4), 4: (1, 3, 5), 5: (2, 4)}
seen = {start}
queue = deque([(start, 0)])
while queue:
state, moves = queue.popleft()
if state == goal:
return moves
z = state.index("0")
for j in neighbors[z]:
cells = list(state)
cells[z], cells[j] = cells[j], cells[z]
nxt = "".join(cells)
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, moves + 1))
return -1function fewestSlides(board) {
const start = board.flat().join("");
const goal = "123450";
const neighbors = [[1, 3], [0, 2, 4], [1, 5], [0, 4], [1, 3, 5], [2, 4]];
const seen = new Set([start]);
let frontier = [start];
for (let moves = 0; frontier.length; moves++) {
const next = [];
for (const state of frontier) {
if (state === goal) return moves;
const z = state.indexOf("0");
for (const j of neighbors[z]) {
const cells = state.split("");
[cells[z], cells[j]] = [cells[j], cells[z]];
const key = cells.join("");
if (!seen.has(key)) {
seen.add(key);
next.push(key);
}
}
}
frontier = next;
}
return -1;
}The parity shortcut for impossible boards
Read the five tiles in row order, skipping the blank, and count inversions: pairs where a larger number comes before a smaller one. On a board that is three cells wide, a horizontal slide does not change the reading order at all, and a vertical slide moves one tile past exactly two others, so the inversion count changes by an even number or not at all. The goal has zero inversions, so a board with an odd count can never be solved. Checking all 720 arrangements confirms that the even ones are exactly the solvable ones, which is why BFS from the goal reaches only 360 boards.
def is_solvable(board):
tiles = [v for row in board for v in row if v != 0]
inversions = sum(1 for i in range(len(tiles))
for j in range(i + 1, len(tiles)) if tiles[i] > tiles[j])
return inversions % 2 == 0Mention this as a follow-up rather than leading with it. The interviewer mostly wants the BFS, and the parity rule depends on the board width: on boards with an even number of columns, the row of the blank enters the formula too.
Complexity
| Approach | 2 by 3 board | General board |
|---|---|---|
| BFS over strings | At most 720 states, each with at most 3 neighbors | O((RC)! · RC) time and space, since each state is a string of length RC |
| Iterative deepening | Fast enough here, with repeated work | Exponential in the answer depth |
| Parity check | Constant | O((RC)²) with the simple count |
For larger puzzles such as the 4 by 4 version, plain BFS is no longer practical. The usual next step is A* or IDA* with the Manhattan distance heuristic, which is a good thing to name if the interviewer asks how the idea scales.
Edge cases to test
- The board is already solved: return 0 without exploring.
- A board one slide away, to confirm depths start counting at 0.
- An unsolvable board with a single swapped pair, which must return -1 rather than loop.
- The blank in each of the six positions, to catch a typo in the neighbor table.
- The farthest solvable boards, which need 21 moves on this tray.
Common mistakes
- Using a list as the state. Lists are not hashable in Python, and comparing arrays by reference in JavaScript never matches.
- Computing neighbors with row and column math and letting the blank wrap from position 2 to position 3, which are not adjacent.
- Marking a board seen when it is popped rather than when it is pushed, which lets duplicates flood the queue.
- Forgetting the -1 case and assuming every board is solvable.
- Using DFS and returning the first solution found, which is rarely the shortest.
A short spoken walkthrough
Fictional example
- Candidate
- Each whole board is a node, and a slide is an edge with cost one. So the fewest moves is a shortest path in an unweighted graph, which means BFS.
- Candidate
- I will flatten the board to a string so it can go in a set, and hard-code which of the six positions touch each other. Then I swap the zero with each neighbor and push new strings.
- Interviewer
- What if the puzzle can't be solved?
- Candidate
- Then BFS runs out of states, and I return -1. There are only 720 arrangements, so that is cheap. There is also an inversion-parity test that answers it up front.
Related problems in this set
If modeling a word as a node felt natural, Word Ladder II pushes the same idea further by returning every shortest route instead of just its length. A grid walk repeated between several targets in a fixed order is the heart of Cut Off Trees for Golf Event. The data structure interview questions page covers the queues and hash sets these searches depend on.
Practice this with Natively
Natively can look at a screenshot of a puzzle prompt during a practice session and propose how to model the state, which is a useful check once you have sketched your own BFS on paper. Its transcript of a recorded mock round on your computer shows whether you explained why BFS gives the minimum before you started coding. More detail lives on the AI interview assistant page.
Questions people ask
What algorithm solves the Sliding Puzzle problem?
Breadth-first search over board states. Each arrangement of the 2 by 3 board is a node, each slide is an edge, and the first time BFS reaches the solved board its depth is the fewest moves.
How do you store a board in a visited set?
Flatten it row by row into a six-character string such as "103425". Strings are hashable, cheap to compare, and easy to swap characters in.
How can you tell a sliding puzzle board is unsolvable?
Count inversions among the tiles in reading order, ignoring the blank. On a three-column board the count keeps its parity under every slide, so an odd count can never reach the solved board.
What is the complexity of the BFS solution?
The 2 by 3 board has only 720 arrangements, and at most 360 are reachable from any start, so time and space are bounded by a small constant. On a general R by C board the state space grows factorially, which is why larger puzzles use A* instead.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
