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.
Move from brute-force thinking to an efficient approach using array strategy.
Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
Example 1:
Input: grid = [[0,0,1],[1,1,0],[1,0,0]] Output: 3
Example 2:
Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]] Output: -1 Explanation: All rows are similar, swaps have no effect on the grid.
Example 3:
Input: grid = [[1,0,0],[1,1,0],[1,1,1]] Output: 0
Constraints:
n == grid.length == grid[i].length1 <= n <= 200grid[i][j] is either 0 or 1Problem summary: Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them. A grid is said to be valid if all the cells above the main diagonal are zeros. Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid. The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[[0,0,1],[1,1,0],[1,0,0]]
[[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]
[[1,0,0],[1,1,0],[1,1,1]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1536: Minimum Swaps to Arrange a Binary Grid
class Solution {
public int minSwaps(int[][] grid) {
int n = grid.length;
int[] pos = new int[n];
Arrays.fill(pos, -1);
for (int i = 0; i < n; ++i) {
for (int j = n - 1; j >= 0; --j) {
if (grid[i][j] == 1) {
pos[i] = j;
break;
}
}
}
int ans = 0;
for (int i = 0; i < n; ++i) {
int k = -1;
for (int j = i; j < n; ++j) {
if (pos[j] <= i) {
ans += j - i;
k = j;
break;
}
}
if (k == -1) {
return -1;
}
for (; k > i; --k) {
int t = pos[k];
pos[k] = pos[k - 1];
pos[k - 1] = t;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1536: Minimum Swaps to Arrange a Binary Grid
func minSwaps(grid [][]int) (ans int) {
n := len(grid)
pos := make([]int, n)
for i := range pos {
pos[i] = -1
}
for i := 0; i < n; i++ {
for j := n - 1; j >= 0; j-- {
if grid[i][j] == 1 {
pos[i] = j
break
}
}
}
for i := 0; i < n; i++ {
k := -1
for j := i; j < n; j++ {
if pos[j] <= i {
ans += j - i
k = j
break
}
}
if k == -1 {
return -1
}
for ; k > i; k-- {
pos[k], pos[k-1] = pos[k-1], pos[k]
}
}
return
}
# Accepted solution for LeetCode #1536: Minimum Swaps to Arrange a Binary Grid
class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
n = len(grid)
pos = [-1] * n
for i in range(n):
for j in range(n - 1, -1, -1):
if grid[i][j] == 1:
pos[i] = j
break
ans = 0
for i in range(n):
k = -1
for j in range(i, n):
if pos[j] <= i:
ans += j - i
k = j
break
if k == -1:
return -1
while k > i:
pos[k], pos[k - 1] = pos[k - 1], pos[k]
k -= 1
return ans
// Accepted solution for LeetCode #1536: Minimum Swaps to Arrange a Binary Grid
struct Solution;
impl Solution {
fn min_swaps(mut grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
let mut res = 0;
'outer: for i in 0..n {
for j in i..n {
if grid[j][i + 1..].iter().all(|&x| x == 0) {
let mut k = j;
while k > i {
grid.swap(k, k - 1);
res += 1;
k -= 1;
}
continue 'outer;
}
}
return -1;
}
res as i32
}
}
#[test]
fn test() {
let grid = vec_vec_i32![[0, 0, 1], [1, 1, 0], [1, 0, 0]];
let res = 3;
assert_eq!(Solution::min_swaps(grid), res);
let grid = vec_vec_i32![
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1]
];
let res = 4;
assert_eq!(Solution::min_swaps(grid), res);
let grid = vec_vec_i32![[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0]];
let res = -1;
assert_eq!(Solution::min_swaps(grid), res);
let grid = vec_vec_i32![[1, 0, 0], [1, 1, 0], [1, 1, 1]];
let res = 0;
assert_eq!(Solution::min_swaps(grid), res);
}
// Accepted solution for LeetCode #1536: Minimum Swaps to Arrange a Binary Grid
function minSwaps(grid: number[][]): number {
const n = grid.length;
const pos: number[] = Array(n).fill(-1);
for (let i = 0; i < n; ++i) {
for (let j = n - 1; ~j; --j) {
if (grid[i][j] === 1) {
pos[i] = j;
break;
}
}
}
let ans = 0;
for (let i = 0; i < n; ++i) {
let k = -1;
for (let j = i; j < n; ++j) {
if (pos[j] <= i) {
ans += j - i;
k = j;
break;
}
}
if (k === -1) {
return -1;
}
for (; k > i; --k) {
[pos[k], pos[k - 1]] = [pos[k - 1], pos[k]];
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
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: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.