Minimum Swaps to Arrange a Binary Grid — LeetCode 1536 Python Solution

MediumGreedyArrayMatrix
Problem
#1536
Reading time
4 min

The problem

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.

Example

Input
grid = [[0,0,1],[1,1,0],[1,0,0]]
Output
3

Python solution

Python
class Solution:
    def minSwaps(self, grid: List[List[int]]) -> int:
        n = len(grid)
        pos = [-1] * n
        for i in range(n):
            for j in range(n - 1, -1, -1):
                if grid[i][j] == 1:
                    pos[i] = j
                    break
        ans = 0
        for i in range(n):
            k = -1
            for j in range(i, n):
                if pos[j] <= i:
                    ans += j - i
                    k = j
                    break
            if k == -1:
                return -1
            while k > i:
                pos[k], pos[k - 1] = pos[k - 1], pos[k]
                k -= 1
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1536. Minimum Swaps to Arrange a Binary Grid is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1536. Minimum Swaps to Arrange a Binary Grid?
LeetCode 1536. Minimum Swaps to Arrange a Binary Grid is rated Medium on LeetCode.
What is the time complexity of LeetCode 1536. Minimum Swaps to Arrange a Binary Grid?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1536. Minimum Swaps to Arrange a Binary Grid?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1536. Minimum Swaps to Arrange a Binary Grid cover?
LeetCode 1536. Minimum Swaps to Arrange a Binary Grid is tagged Greedy, Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview