Minimum Swaps to Arrange a Binary Grid Problem
Description
LeetCode Problem 1536.
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 either0or1
Solution
Approach: Greedy, Bubble the Nearest Fitting Row Up
A row only matters through the position of its rightmost 1, call it last. Row i of the final grid is fine when last <= i (an all-zero row has last = -1 and fits anywhere). So first compute last for each row, and forget the grid.
Now fill the positions from the top. Position 0 is the strictest: it needs last <= 0. For position i, pick the first row at or below i with last <= i, say at index k, and move it up with k - i adjacent swaps. The rows between shift down by one but keep their order. If no such row exists, return -1.
Why the nearest fitting row? The requirements only get looser further down, so a row that fits position i also fits every later position: for the rows still to place, all fitting rows are interchangeable. The nearest one costs the fewest swaps now, and moving it up keeps the other rows in their original order.
Complexity: O(n2) time (computing last and the bubbling) and O(n) extra space.
class Solution:
def minSwaps(self, grid: List[List[int]]) -> int:
n = len(grid)
# last[r] = column of the rightmost 1 in row r (-1 for an all-zero row)
last = []
for row in grid:
j = n - 1
while j >= 0 and row[j] == 0:
j -= 1
last.append(j)
swaps = 0
for i in range(n):
# Row i needs its rightmost 1 at column <= i: take the nearest such row below.
k = i
while k < n and last[k] > i:
k += 1
if k == n:
return -1
swaps += k - i
last.insert(i, last.pop(k)) # bubble row k up to position i
return swaps