Reorder the rows of a binary grid using adjacent row swaps so that each row has enough trailing zeros below the diagonal requirement.
Problem
You are given an binary grid. In one move, you may swap two adjacent rows.
A grid is considered valid if for every row (0-indexed), the number of trailing zeros in that row is at least .
Return the minimum number of adjacent row swaps needed to make the grid valid, or if it is impossible.
Clarification
For a row, the number of trailing zeros is the count of consecutive 0 values at the end of the row.
The goal is to arrange the rows so the top row has the most restrictive requirement, the next row slightly less restrictive, and so on.
Input Format
An integer and an binary grid represented as a 2D array of 0s and 1s.
Output Format
Return a single integer: the minimum number of adjacent row swaps required, or -1 if no valid arrangement exists.
Constraints
The grid is square and contains only 0 and 1 values.
Common interview formulation: .
Example 1
Input
grid = [[0,0,1],[1,1,0],[1,0,0]]
Output
3
Explanation
Trailing zeros per row are [0,1,2]. To satisfy requirements [2,1,0], move the row with 2 trailing zeros to the top using 2 swaps, then the row with 1 trailing zero to position 1 using 1 more swap.
Example 2
Input
grid = [[0,1,1],[1,0,1],[1,1,0]]
Output
-1
Explanation
Trailing zeros per row are [0,0,1]. The top row needs at least 2 trailing zeros, which does not exist, so the grid cannot be made valid.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.