Minimum Swaps to Arrange a Binary Grid — LeetCode 1536 Python Solution
MediumGreedyArrayMatrix
- Problem
- #1536
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(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
LeetCode 807Max Increase to Keep City SkylineMediumLeetCode 861Score After Flipping MatrixMediumLeetCode 1253Reconstruct a 2-Row Binary MatrixMediumLeetCode 1605Find Valid Matrix Given Row and Column SumsMediumLeetCode 1727Largest Submatrix With RearrangementsMediumLeetCode 1975Maximum Matrix SumMedium
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.