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
Minimum Swaps to Arrange Binary Grid INPUT 3x4 Binary Grid: 0 1 1 0 0 0 0 1 1 0 0 0 Main diagonal shown Trailing Zeros: Row 0: 1 trailing zero Row 1: 0 trailing zeros Row 2: 3 trailing zeros zeros = [1, 0, 3] ALGORITHM STEPS 1 Count Trailing Zeros For each row, count zeros from rightmost position 2 Greedy Selection For row i, need n-i-1 trailing zeros minimum 3 Find Valid Row Find closest row with enough trailing zeros 4 Bubble Up Swap adjacent rows to move valid row up Swaps: Swap 1: R1,R2 Swap 2: R0,R1 FINAL RESULT Valid Grid (after 2 swaps): 1 0 0 0 0 1 1 0 0 0 0 1 All zeros above diagonal - OK Output 2 Minimum swaps needed Grid is now VALID Key Insight: For a valid grid, row i needs at least (n-i-1) trailing zeros. Use greedy approach: find the closest row with enough trailing zeros and bubble it up with adjacent swaps. TutorialsPoint - Minimum Swaps to Arrange a Binary Grid | Greedy - Count Trailing Zeros
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