Minimum Adjacent Row Swaps for Zeros Above the Diagonal

Quick Overview

Minimum Adjacent Row Swaps for Zeros Above the Diagonal. You may swap only neighboring rows of the square binary grid.

Minimum Adjacent Row Swaps for Zeros Above the Diagonal

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem You may swap only neighboring rows of the square binary grid. A valid arrangement has 0 in every cell strictly above the main diagonal. Return the fewest row swaps needed,or -1 when impossible. Column order cannot change. ```cpp class Solution { public: int minSwaps(vector<vector<int>>& grid); }; ``` ### Examples **Example 1:** ```text Input: grid = [[0,1],[1,0]] Output: 1 Explanation: Swap the two rows so the top-right cell is0. ``` **Example 2:** ```text Input: grid = [[1,1],[1,1]] Output: -1 Explanation: Neither row has a trailing zero for the first position. ``` ### Constraints - grid is n by n,with `1 <= n <= 200`. - Every grid entry is 0 or 1. ### Contract considerations Rows may contain arbitrary binary patterns before their trailing-zero suffix. ```hint Read the boundary condition Only adjacent row swaps are legal. Check every cell above the diagonal, all-zero rows, and arrangements that cannot be made valid. ``` ### Boundary reminders Rows may contain arbitrary binary patterns before their trailing-zero suffix.

Overview: Minimum Adjacent Row Swaps for Zeros Above the Diagonal. You may swap only neighboring rows of the square binary grid.

Amazon logo
Amazon
Source window: 0–6 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

You may swap only neighboring rows of the square binary grid. A valid arrangement has 0 in every cell strictly above the main diagonal. Return the fewest row swaps needed,or -1 when impossible. Column order cannot change.

class Solution {
public:
    int minSwaps(vector<vector<int>>& grid);
};

Examples

Example 1:

Input: grid = [[0,1],[1,0]]
Output: 1
Explanation: Swap the two rows so the top-right cell is0.

Example 2:

Input: grid = [[1,1],[1,1]]
Output: -1
Explanation: Neither row has a trailing zero for the first position.

Constraints

  • grid is n by n,with 1 <= n <= 200 .
  • Every grid entry is 0 or 1.

Contract considerations

Rows may contain arbitrary binary patterns before their trailing-zero suffix.

Boundary reminders

Rows may contain arbitrary binary patterns before their trailing-zero suffix.