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
Binary Grid: Make Upper Triangle All ZerosInvalid Grid011001100Valid Grid100000010❌ Has 1s above diagonal✅ Only 0s above diagonalAdjacent Row Swaps2 swaps to rearrange rowsStrategy: Count trailing zeros in each rowRow i needs ≥ (n-1-i) trailing zeros to be valid at position i🎯 Key Insight: Greedy placement based on trailing zero count minimizes swaps
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
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen