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.
You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]] Output: 2 Explanation: One potential sequence of moves is shown. The first move swaps the first and second column. The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]] Output: 0 Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]] Output: -1 Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Constraints:
n == board.lengthn == board[i].length2 <= n <= 30board[i][j] is either 0 or 1.Problem summary: You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1. A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Bit Manipulation
[[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
[[0,1],[1,0]]
[[1,0],[1,0]]
minimum-moves-to-get-a-peaceful-board)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #782: Transform to Chessboard
class Solution {
private int n;
public int movesToChessboard(int[][] board) {
n = board.length;
int mask = (1 << n) - 1;
int rowMask = 0, colMask = 0;
for (int i = 0; i < n; ++i) {
rowMask |= board[0][i] << i;
colMask |= board[i][0] << i;
}
int revRowMask = mask ^ rowMask;
int revColMask = mask ^ colMask;
int sameRow = 0, sameCol = 0;
for (int i = 0; i < n; ++i) {
int curRowMask = 0, curColMask = 0;
for (int j = 0; j < n; ++j) {
curRowMask |= board[i][j] << j;
curColMask |= board[j][i] << j;
}
if (curRowMask != rowMask && curRowMask != revRowMask) {
return -1;
}
if (curColMask != colMask && curColMask != revColMask) {
return -1;
}
sameRow += curRowMask == rowMask ? 1 : 0;
sameCol += curColMask == colMask ? 1 : 0;
}
int t1 = f(rowMask, sameRow);
int t2 = f(colMask, sameCol);
return t1 == -1 || t2 == -1 ? -1 : t1 + t2;
}
private int f(int mask, int cnt) {
int ones = Integer.bitCount(mask);
if (n % 2 == 1) {
if (Math.abs(n - ones * 2) != 1 || Math.abs(n - cnt * 2) != 1) {
return -1;
}
if (ones == n / 2) {
return n / 2 - Integer.bitCount(mask & 0xAAAAAAAA);
}
return (n / 2 + 1) - Integer.bitCount(mask & 0x55555555);
} else {
if (ones != n / 2 || cnt != n / 2) {
return -1;
}
int cnt0 = n / 2 - Integer.bitCount(mask & 0xAAAAAAAA);
int cnt1 = n / 2 - Integer.bitCount(mask & 0x55555555);
return Math.min(cnt0, cnt1);
}
}
}
// Accepted solution for LeetCode #782: Transform to Chessboard
func movesToChessboard(board [][]int) int {
n := len(board)
mask := (1 << n) - 1
rowMask, colMask := 0, 0
for i := 0; i < n; i++ {
rowMask |= board[0][i] << i
colMask |= board[i][0] << i
}
revRowMask := mask ^ rowMask
revColMask := mask ^ colMask
sameRow, sameCol := 0, 0
for i := 0; i < n; i++ {
curRowMask, curColMask := 0, 0
for j := 0; j < n; j++ {
curRowMask |= board[i][j] << j
curColMask |= board[j][i] << j
}
if curRowMask != rowMask && curRowMask != revRowMask {
return -1
}
if curColMask != colMask && curColMask != revColMask {
return -1
}
if curRowMask == rowMask {
sameRow++
}
if curColMask == colMask {
sameCol++
}
}
f := func(mask, cnt int) int {
ones := bits.OnesCount(uint(mask))
if n%2 == 1 {
if abs(n-ones*2) != 1 || abs(n-cnt*2) != 1 {
return -1
}
if ones == n/2 {
return n/2 - bits.OnesCount(uint(mask&0xAAAAAAAA))
}
return (n+1)/2 - bits.OnesCount(uint(mask&0x55555555))
} else {
if ones != n/2 || cnt != n/2 {
return -1
}
cnt0 := n/2 - bits.OnesCount(uint(mask&0xAAAAAAAA))
cnt1 := n/2 - bits.OnesCount(uint(mask&0x55555555))
return min(cnt0, cnt1)
}
}
t1 := f(rowMask, sameRow)
t2 := f(colMask, sameCol)
if t1 == -1 || t2 == -1 {
return -1
}
return t1 + t2
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #782: Transform to Chessboard
class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
def f(mask, cnt):
ones = mask.bit_count()
if n & 1:
if abs(n - 2 * ones) != 1 or abs(n - 2 * cnt) != 1:
return -1
if ones == n // 2:
return n // 2 - (mask & 0xAAAAAAAA).bit_count()
return (n + 1) // 2 - (mask & 0x55555555).bit_count()
else:
if ones != n // 2 or cnt != n // 2:
return -1
cnt0 = n // 2 - (mask & 0xAAAAAAAA).bit_count()
cnt1 = n // 2 - (mask & 0x55555555).bit_count()
return min(cnt0, cnt1)
n = len(board)
mask = (1 << n) - 1
rowMask = colMask = 0
for i in range(n):
rowMask |= board[0][i] << i
colMask |= board[i][0] << i
revRowMask = mask ^ rowMask
revColMask = mask ^ colMask
sameRow = sameCol = 0
for i in range(n):
curRowMask = curColMask = 0
for j in range(n):
curRowMask |= board[i][j] << j
curColMask |= board[j][i] << j
if curRowMask not in (rowMask, revRowMask) or curColMask not in (
colMask,
revColMask,
):
return -1
sameRow += curRowMask == rowMask
sameCol += curColMask == colMask
t1 = f(rowMask, sameRow)
t2 = f(colMask, sameCol)
return -1 if t1 == -1 or t2 == -1 else t1 + t2
// Accepted solution for LeetCode #782: Transform to Chessboard
/**
* [0782] Transform to Chessboard
*
* You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.
* Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
* A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/chessboard1-grid.jpg" style="width: 500px; height: 145px;" />
* Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
* Output: 2
* Explanation: One potential sequence of moves is shown.
* The first move swaps the first and second column.
* The second move swaps the second and third row.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/chessboard2-grid.jpg" style="width: 164px; height: 165px;" />
* Input: board = [[0,1],[1,0]]
* Output: 0
* Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
*
* Example 3:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/chessboard3-grid.jpg" style="width: 164px; height: 165px;" />
* Input: board = [[1,0],[1,0]]
* Output: -1
* Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
*
*
* Constraints:
*
* n == board.length
* n == board[i].length
* 2 <= n <= 30
* board[i][j] is either 0 or 1.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/transform-to-chessboard/
// discuss: https://leetcode.com/problems/transform-to-chessboard/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/transform-to-chessboard/discuss/1487590/Rust-translated
pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 {
let n = board.len();
for i in 1..n {
if (1..n as i32).contains(&(0..n).map(|j| board[i][j] ^ board[0][j]).sum::<i32>()) {
return -1;
}
if (1..n as i32).contains(&(0..n).map(|j| board[j][i] ^ board[j][0]).sum::<i32>()) {
return -1;
}
}
if ((0..n).map(|i| board[0][i]).sum::<i32>() * 2 - n as i32).abs() > 1 {
return -1;
}
if ((0..n).map(|i| board[i][0]).sum::<i32>() * 2 - n as i32).abs() > 1 {
return -1;
}
let mut rowdiff = (0..n).filter(|&i| board[0][i] == i as i32 % 2).count();
if rowdiff % 2 != 0 || (n % 2 == 0 && rowdiff * 2 > n) {
rowdiff = n - rowdiff;
}
let mut coldiff = (0..n).filter(|&i| board[i][0] == i as i32 % 2).count();
if coldiff % 2 != 0 || (n % 2 == 0 && coldiff * 2 > n) {
coldiff = n - coldiff;
}
(rowdiff + coldiff) as i32 / 2
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0782_example_1() {
let board = vec![
vec![0, 1, 1, 0],
vec![0, 1, 1, 0],
vec![1, 0, 0, 1],
vec![1, 0, 0, 1],
];
let result = 2;
assert_eq!(Solution::moves_to_chessboard(board), result);
}
#[test]
fn test_0782_example_2() {
let board = vec![vec![0, 1], vec![1, 0]];
let result = 0;
assert_eq!(Solution::moves_to_chessboard(board), result);
}
#[test]
fn test_0782_example_3() {
let board = vec![vec![1, 0], vec![1, 0]];
let result = -1;
assert_eq!(Solution::moves_to_chessboard(board), result);
}
}
// Accepted solution for LeetCode #782: Transform to Chessboard
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #782: Transform to Chessboard
// class Solution {
// private int n;
//
// public int movesToChessboard(int[][] board) {
// n = board.length;
// int mask = (1 << n) - 1;
// int rowMask = 0, colMask = 0;
// for (int i = 0; i < n; ++i) {
// rowMask |= board[0][i] << i;
// colMask |= board[i][0] << i;
// }
// int revRowMask = mask ^ rowMask;
// int revColMask = mask ^ colMask;
// int sameRow = 0, sameCol = 0;
// for (int i = 0; i < n; ++i) {
// int curRowMask = 0, curColMask = 0;
// for (int j = 0; j < n; ++j) {
// curRowMask |= board[i][j] << j;
// curColMask |= board[j][i] << j;
// }
// if (curRowMask != rowMask && curRowMask != revRowMask) {
// return -1;
// }
// if (curColMask != colMask && curColMask != revColMask) {
// return -1;
// }
// sameRow += curRowMask == rowMask ? 1 : 0;
// sameCol += curColMask == colMask ? 1 : 0;
// }
// int t1 = f(rowMask, sameRow);
// int t2 = f(colMask, sameCol);
// return t1 == -1 || t2 == -1 ? -1 : t1 + t2;
// }
//
// private int f(int mask, int cnt) {
// int ones = Integer.bitCount(mask);
// if (n % 2 == 1) {
// if (Math.abs(n - ones * 2) != 1 || Math.abs(n - cnt * 2) != 1) {
// return -1;
// }
// if (ones == n / 2) {
// return n / 2 - Integer.bitCount(mask & 0xAAAAAAAA);
// }
// return (n / 2 + 1) - Integer.bitCount(mask & 0x55555555);
// } else {
// if (ones != n / 2 || cnt != n / 2) {
// return -1;
// }
// int cnt0 = n / 2 - Integer.bitCount(mask & 0xAAAAAAAA);
// int cnt1 = n / 2 - Integer.bitCount(mask & 0x55555555);
// return Math.min(cnt0, cnt1);
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
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: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.