#1536

Minimum Swaps to Arrange a Binary Grid

Medium
ArrayGreedyMatrixGreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach leverages the sorted order of the rightmost '1' indices to minimize swaps. By ensuring that each row's maxRight value is less than or equal to its index, we can efficiently count the necessary swaps.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the rightmost '1' for each row and store it in an array maxRight.
  2. 2Step 2: Sort the maxRight array.
  3. 3Step 3: For each index i in the sorted maxRight, ensure that maxRight[i] <= i. If not, return -1.
  4. 4Step 4: Count the number of swaps needed to arrange the rows based on the maxRight values.
solution.py18 lines
1def minSwaps(grid):
2    n = len(grid)
3    maxRight = [0] * n
4    for i in range(n):
5        for j in range(n - 1, -1, -1):
6            if grid[i][j] == 1:
7                maxRight[i] = j
8                break
9    sortedMaxRight = sorted(maxRight)
10    for i in range(n):
11        if sortedMaxRight[i] > i:
12            return -1
13    swaps = 0
14    for i in range(n):
15        while maxRight[i] != sortedMaxRight[i]:
16            swaps += 1
17            maxRight[i], maxRight[i + 1] = maxRight[i + 1], maxRight[i]
18    return swaps

Complexity note: The time complexity is O(n log n) due to sorting the maxRight array, and the space complexity is O(n) for storing the maxRight values.

  • 1The rightmost '1' in each row determines the validity of the grid.
  • 2Sorting the maxRight values helps in minimizing the number of swaps.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.