← Questions

Sliding puzzle on a 2 by 3 board

0
AirbnbCodingLast asked Apr 2026

A coding interview question asked in Airbnb's coding round, last asked Apr 2026. It tests bfs and state search.

A 2 by 3 board holds the numbers 0 to 5, each once; 0 is the empty square. A move swaps 0 with a number directly above, below, left or right of it. Return the fewest moves to reach [[1, 2, 3], [4, 5, 0]], or -1 if it can't be reached.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • sliding_puzzle(board: list[list[int]]) -> int: 0 when the board is already solved.

Example

[[1, 2, 3], [4, 0, 5]]  ->  1
[[1, 2, 3], [0, 4, 5]]  ->  2
[[4, 1, 2], [5, 0, 3]]  ->  5
[[1, 2, 3], [5, 4, 0]]  ->  -1     # wrong parity: unreachable

Constraints

  • Exactly two rows and three columns; every number from 0 to 5 appears once.

Clarifying questions

  • Should I return the moves themselves, or only the count?
  • May I modify the input board?

What a strong answer covers

  • Each arrangement is a node in an unweighted graph: BFS from the start finds the shortest path.
  • A compact state, such as the string "123450", and a precomputed list of neighbors for each position of 0.
  • A visited set; at most 6! = 720 states, so the search is tiny.
  • Why half the arrangements are unreachable (permutation parity), and checking parity up front.
  • Tests: already solved, one move, unreachable.

Follow-ups

  • Return the sequence of moves.
  • Solve a 3 by 3 or 4 by 4 board, where BFS is too slow: A* with Manhattan distance.
  • Run BFS from both ends.

Where it's asked

  • Airbnb · Coding · Last asked Apr 202645 min · Live coding, one or two rounds, from the same pool as the screen

What it tests

bfs · state search

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