Minimum Swaps to Arrange a Binary Grid - Problem
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).
Input & Output
Example 1 — Basic Grid Arrangement
$
Input:
grid = [[0,1,1,0],[0,0,0,1],[1,0,0,0]]
›
Output:
2
💡 Note:
Row 2 [1,0,0,0] has 3 trailing zeros, perfect for position 0. We swap row 2 with row 1 (1 swap), then row 1 with row 0 (1 swap), giving us 2 total swaps.
Example 2 — Already Valid Grid
$
Input:
grid = [[1,0,0],[0,1,0],[0,0,1]]
›
Output:
0
💡 Note:
The grid is already valid - all cells above the main diagonal are zeros. No swaps needed.
Example 3 — Impossible Case
$
Input:
grid = [[1,1,1],[0,0,0],[1,1,1]]
›
Output:
-1
💡 Note:
Row 0 needs ≥2 trailing zeros but [1,1,1] has 0. Row 2 [1,1,1] also has 0. No valid arrangement possible.
Constraints
- n == grid.length
- n == grid[i].length
- 1 ≤ n ≤ 200
- grid[i][j] is 0 or 1
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
Binary grid with 1s above diagonal
2
Valid Constraint
All cells above main diagonal must be 0
3
Adjacent Swaps
Minimum swaps to achieve valid state
Key Takeaway
🎯 Key Insight: Count trailing zeros in each row - this determines the minimum position where each row can be validly placed
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code