Skip to main content
Back to problems
Leetcode
Medium
Arrays
Greedy
Matrices
Minimum Swaps To Arrange A Binary Grid

Reorder the rows of a binary grid using adjacent row swaps so that each row has enough trailing zeros below the diagonal requirement.

Acceptance 0%
Problem Statement

Problem

You are given an n×nn \times n binary grid. In one move, you may swap two adjacent rows.

A grid is considered valid if for every row ii (0-indexed), the number of trailing zeros in that row is at least n1in - 1 - i.

Return the minimum number of adjacent row swaps needed to make the grid valid, or 1-1 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 nn and an n×nn \times n 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: 1n2001 \le n \le 200.

Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.