Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Example 1:
Input: board = [[1,2,3],[4,0,5]] Output: 1 Explanation: Swap the 0 and the 5 in one move.
Example 2:
Input: board = [[1,2,3],[5,4,0]] Output: -1 Explanation: No number of moves will make the board solved.
Example 3:
Input: board = [[4,1,2],[5,0,3]] Output: 5 Explanation: 5 is the smallest number of moves that solves the board. An example path: After move 0: [[4,1,2],[5,0,3]] After move 1: [[4,1,2],[0,5,3]] After move 2: [[0,1,2],[4,5,3]] After move 3: [[1,0,2],[4,5,3]] After move 4: [[1,2,0],[4,5,3]] After move 5: [[1,2,3],[4,5,0]]
Constraints:
board.length == 2board[i].length == 30 <= board[i][j] <= 5board[i][j] is unique.Problem summary: On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Backtracking
[[1,2,3],[4,0,5]]
[[1,2,3],[5,4,0]]
[[4,1,2],[5,0,3]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #773: Sliding Puzzle
class Solution {
private String[] t = new String[6];
private int[][] board;
public int slidingPuzzle(int[][] board) {
this.board = board;
String start = gets();
String end = "123450";
if (end.equals(start)) {
return 0;
}
Set<String> vis = new HashSet<>();
Deque<String> q = new ArrayDeque<>();
q.offer(start);
vis.add(start);
int ans = 0;
while (!q.isEmpty()) {
++ans;
for (int n = q.size(); n > 0; --n) {
String x = q.poll();
setb(x);
for (String y : next()) {
if (y.equals(end)) {
return ans;
}
if (!vis.contains(y)) {
vis.add(y);
q.offer(y);
}
}
}
}
return -1;
}
private String gets() {
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
t[i * 3 + j] = String.valueOf(board[i][j]);
}
}
return String.join("", t);
}
private void setb(String s) {
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
board[i][j] = s.charAt(i * 3 + j) - '0';
}
}
}
private int[] find0() {
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i][j] == 0) {
return new int[] {i, j};
}
}
}
return new int[] {0, 0};
}
private List<String> next() {
int[] p = find0();
int i = p[0], j = p[1];
int[] dirs = {-1, 0, 1, 0, -1};
List<String> res = new ArrayList<>();
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k];
int y = j + dirs[k + 1];
if (x >= 0 && x < 2 && y >= 0 && y < 3) {
swap(i, j, x, y);
res.add(gets());
swap(i, j, x, y);
}
}
return res;
}
private void swap(int i, int j, int x, int y) {
int t = board[i][j];
board[i][j] = board[x][y];
board[x][y] = t;
}
}
// Accepted solution for LeetCode #773: Sliding Puzzle
// Auto-generated Go example from java.
func exampleSolution() {
}
// Reference (java):
// // Accepted solution for LeetCode #773: Sliding Puzzle
// class Solution {
// private String[] t = new String[6];
// private int[][] board;
//
// public int slidingPuzzle(int[][] board) {
// this.board = board;
// String start = gets();
// String end = "123450";
// if (end.equals(start)) {
// return 0;
// }
// Set<String> vis = new HashSet<>();
// Deque<String> q = new ArrayDeque<>();
// q.offer(start);
// vis.add(start);
// int ans = 0;
// while (!q.isEmpty()) {
// ++ans;
// for (int n = q.size(); n > 0; --n) {
// String x = q.poll();
// setb(x);
// for (String y : next()) {
// if (y.equals(end)) {
// return ans;
// }
// if (!vis.contains(y)) {
// vis.add(y);
// q.offer(y);
// }
// }
// }
// }
// return -1;
// }
//
// private String gets() {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// t[i * 3 + j] = String.valueOf(board[i][j]);
// }
// }
// return String.join("", t);
// }
//
// private void setb(String s) {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// board[i][j] = s.charAt(i * 3 + j) - '0';
// }
// }
// }
//
// private int[] find0() {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// if (board[i][j] == 0) {
// return new int[] {i, j};
// }
// }
// }
// return new int[] {0, 0};
// }
//
// private List<String> next() {
// int[] p = find0();
// int i = p[0], j = p[1];
// int[] dirs = {-1, 0, 1, 0, -1};
// List<String> res = new ArrayList<>();
// for (int k = 0; k < 4; ++k) {
// int x = i + dirs[k];
// int y = j + dirs[k + 1];
// if (x >= 0 && x < 2 && y >= 0 && y < 3) {
// swap(i, j, x, y);
// res.add(gets());
// swap(i, j, x, y);
// }
// }
// return res;
// }
//
// private void swap(int i, int j, int x, int y) {
// int t = board[i][j];
// board[i][j] = board[x][y];
// board[x][y] = t;
// }
// }
# Accepted solution for LeetCode #773: Sliding Puzzle
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
t = [None] * 6
def gets():
for i in range(2):
for j in range(3):
t[i * 3 + j] = str(board[i][j])
return ''.join(t)
def setb(s):
for i in range(2):
for j in range(3):
board[i][j] = int(s[i * 3 + j])
def f():
res = []
i, j = next((i, j) for i in range(2) for j in range(3) if board[i][j] == 0)
for a, b in [[0, -1], [0, 1], [1, 0], [-1, 0]]:
x, y = i + a, j + b
if 0 <= x < 2 and 0 <= y < 3:
board[i][j], board[x][y] = board[x][y], board[i][j]
res.append(gets())
board[i][j], board[x][y] = board[x][y], board[i][j]
return res
start = gets()
end = "123450"
if start == end:
return 0
vis = {start}
q = deque([start])
ans = 0
while q:
ans += 1
for _ in range(len(q)):
x = q.popleft()
setb(x)
for y in f():
if y == end:
return ans
if y not in vis:
vis.add(y)
q.append(y)
return -1
// Accepted solution for LeetCode #773: Sliding Puzzle
struct Solution;
use std::collections::HashSet;
use std::collections::VecDeque;
impl Solution {
fn sliding_puzzle(board: Vec<Vec<i32>>) -> i32 {
let mut visited: HashSet<Vec<i32>> = HashSet::new();
let next = vec![
vec![1, 3],
vec![0, 4, 2],
vec![1, 5],
vec![0, 4],
vec![3, 1, 5],
vec![2, 4],
];
let solved = vec![1, 2, 3, 4, 5, 0];
let mut queue: VecDeque<(Vec<i32>, usize, i32)> = VecDeque::new();
let mut line = vec![];
board
.into_iter()
.for_each(|v| v.into_iter().for_each(|x| line.push(x)));
let zero = line.iter().position(|&x| x == 0).unwrap();
visited.insert(line.to_vec());
queue.push_back((line, zero, 0));
while let Some((line, zero, count)) = queue.pop_front() {
if line == solved {
return count;
}
for &index in &next[zero] {
let mut copy = line.to_vec();
copy.swap(index, zero);
if visited.insert(copy.to_vec()) {
queue.push_back((copy, index, count + 1));
}
}
}
-1
}
}
#[test]
fn test() {
let board = vec_vec_i32![[1, 2, 3], [4, 0, 5]];
let res = 1;
assert_eq!(Solution::sliding_puzzle(board), res);
let board = vec_vec_i32![[1, 2, 3], [5, 4, 0]];
let res = -1;
assert_eq!(Solution::sliding_puzzle(board), res);
let board = vec_vec_i32![[4, 1, 2], [5, 0, 3]];
let res = 5;
assert_eq!(Solution::sliding_puzzle(board), res);
let board = vec_vec_i32![[3, 2, 4], [1, 5, 0]];
let res = 14;
assert_eq!(Solution::sliding_puzzle(board), res);
}
// Accepted solution for LeetCode #773: Sliding Puzzle
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #773: Sliding Puzzle
// class Solution {
// private String[] t = new String[6];
// private int[][] board;
//
// public int slidingPuzzle(int[][] board) {
// this.board = board;
// String start = gets();
// String end = "123450";
// if (end.equals(start)) {
// return 0;
// }
// Set<String> vis = new HashSet<>();
// Deque<String> q = new ArrayDeque<>();
// q.offer(start);
// vis.add(start);
// int ans = 0;
// while (!q.isEmpty()) {
// ++ans;
// for (int n = q.size(); n > 0; --n) {
// String x = q.poll();
// setb(x);
// for (String y : next()) {
// if (y.equals(end)) {
// return ans;
// }
// if (!vis.contains(y)) {
// vis.add(y);
// q.offer(y);
// }
// }
// }
// }
// return -1;
// }
//
// private String gets() {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// t[i * 3 + j] = String.valueOf(board[i][j]);
// }
// }
// return String.join("", t);
// }
//
// private void setb(String s) {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// board[i][j] = s.charAt(i * 3 + j) - '0';
// }
// }
// }
//
// private int[] find0() {
// for (int i = 0; i < 2; ++i) {
// for (int j = 0; j < 3; ++j) {
// if (board[i][j] == 0) {
// return new int[] {i, j};
// }
// }
// }
// return new int[] {0, 0};
// }
//
// private List<String> next() {
// int[] p = find0();
// int i = p[0], j = p[1];
// int[] dirs = {-1, 0, 1, 0, -1};
// List<String> res = new ArrayList<>();
// for (int k = 0; k < 4; ++k) {
// int x = i + dirs[k];
// int y = j + dirs[k + 1];
// if (x >= 0 && x < 2 && y >= 0 && y < 3) {
// swap(i, j, x, y);
// res.add(gets());
// swap(i, j, x, y);
// }
// }
// return res;
// }
//
// private void swap(int i, int j, int x, int y) {
// int t = board[i][j];
// board[i][j] = board[x][y];
// board[x][y] = t;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.