Find the largest rectangle of 1's with swapping of columns allowed in Python

Given a binary matrix, we need to find the largest rectangle of all 1's that can be formed by swapping any columns. This problem combines the classic "largest rectangle in histogram" algorithm with column optimization.

Problem Understanding

Consider this matrix ?

1 0 0 1 0
1 0 0 1 1
1 1 0 1 0

By swapping columns 1 and 3, we get ?

0 0 1 1 0
0 0 1 1 1
1 0 1 1 0

This allows us to form a larger rectangle of 1's.

Algorithm

The approach involves three main steps ?

  1. Calculate consecutive 1's: For each column, compute the height of consecutive 1's ending at each row
  2. Sort columns optimally: For each row, arrange columns by height in descending order
  3. Find maximum rectangle: Calculate the largest possible rectangle for each configuration

Implementation

def maxArea(mat):
    row = len(mat)
    col = len(mat[0])
    
    # Create height matrix - stores consecutive 1's height for each position
    temp = [[0 for i in range(col)] for i in range(row)]
    
    # Fill first row
    for i in range(col):
        temp[0][i] = mat[0][i]
    
    # Fill remaining rows
    for i in range(1, row):
        for j in range(col):
            if mat[i][j] == 0:
                temp[i][j] = 0
            else:
                temp[i][j] = temp[i - 1][j] + 1
    
    area_maximum = 0
    
    # For each row, find optimal column arrangement
    for i in range(row):
        # Count frequency of each height
        cnt = [0 for k in range(row + 1)]
        for j in range(col):
            cnt[temp[i][j]] += 1
        
        # Rearrange columns by height (descending order)
        col_no = 0
        for height in range(row, -1, -1):
            if cnt[height] > 0:
                for k in range(cnt[height]):
                    temp[i][col_no] = height
                    col_no += 1
        
        # Calculate maximum area for current row configuration
        for j in range(col):
            area_current = (j + 1) * temp[i][j]
            if area_current > area_maximum:
                area_maximum = area_current
    
    return area_maximum

# Test the function
mat = [
    [1, 0, 0, 1, 0],
    [1, 0, 0, 1, 1],
    [1, 1, 0, 1, 0]
]

print("Maximum rectangle area:", maxArea(mat))
Maximum rectangle area: 6

How It Works

The algorithm works by ?

  1. Height calculation: For each cell, calculate how many consecutive 1's appear above it (including itself)
  2. Optimal sorting: For each row, sort columns by their heights in descending order
  3. Rectangle calculation: For each position (i, j), calculate rectangle area as width × height = (j+1) × temp[i][j]

Example Trace

For the given matrix, the height matrix becomes ?

Original heights:    After optimal sorting for each row:
[1, 0, 0, 1, 0]  ?   [1, 1, 0, 0, 0]
[2, 0, 0, 2, 1]  ?   [2, 2, 1, 0, 0] 
[3, 1, 0, 3, 0]  ?   [3, 3, 1, 0, 0]

The maximum area is found in row 1: width=3 × height=2 = 6.

Conclusion

This algorithm efficiently finds the largest rectangle of 1's by combining height calculation with optimal column arrangement. The time complexity is O(rows × cols) and it handles column swapping by sorting heights optimally for each row.

Updated on: 2026-03-25T09:28:49+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements