Problem Description
Given an n x n binary grid, a grid is defined as valid if all cells above the main diagonal (from top-left to bottom-right) are zeros. In one step, you can swap any two adjacent rows. The goal is to determine the minimum number of swaps required to transform the grid into a valid grid, or return -1 if it is impossible.
Key Insights
- For each row, the position of the rightmost 1 determines the row's constraint. Row i is valid if the rightmost 1 is at or before column i.
- Precompute, for each row, the index of the rightmost 1.
- Use a greedy strategy: for each row position i, find a row below that can be swapped up (using adjacent row swaps) whose rightmost 1 is at an index ≤ i.
- Count the number of swaps involved in moving the valid row upward. If no such row exists for any index, return -1.
Space and Time Complexity
Time Complexity: O(n²) – In the worst case, for each row, a scan (or series of swaps) through the remaining rows is done. Space Complexity: O(n) – For storing the rightmost 1 position for each row.
Solution
We first compute an array that captures, for each row, the index of the rightmost 1. Then, iterate through each row i. For each i, look for a row j below (or at) i such that its rightmost one is found at an index ≤ i. If found, simulate the swaps needed by moving row j upward, counting each adjacent swap. If no such row exists for a particular i, the grid cannot be rearranged to be valid, so return -1. Key data structures include an array for storing rightmost ones. The greedy technique ensures minimal swaps are used by always selecting the closest valid candidate.