Program to find area of largest submatrix by column rearrangements in Python

Suppose we have a binary matrix. We can rearrange the columns as many times as we want, then find the area of the largest submatrix containing only 1s.

So, if the input is like ?

1 0 0
1 1 1
1 0 1

then the output will be 4, because we can arrange it like ?

1 0 0
1 1 1
1 1 0

Algorithm

To solve this, we will follow these steps ?

  • n := row count of matrix
  • m := column count of matrix
  • ans := 0
  • for i in range 1 to n − 1, do
    • for j in range 0 to m − 1, do
      • if matrix[i, j] is 1, then
        • matrix[i, j] := matrix[i, j] + matrix[i−1, j]
  • for each row in matrix, do
    • sort the row
    • for j in range m−1 to 0, decrease by 1, do
      • ans := maximum of ans and row[j] * (m − j)
  • return ans

Implementation

Let us see the following implementation to get better understanding ?

def solve(matrix):
    n, m = len(matrix), len(matrix[0])
    ans = 0
    
    # Calculate consecutive 1s height for each column
    for i in range(1, n):
        for j in range(m):
            if matrix[i][j]:
                matrix[i][j] += matrix[i-1][j]
    
    # For each row, sort and find maximum area
    for row in matrix:
        row.sort()
        for j in range(m-1, -1, -1):
            ans = max(ans, row[j] * (m - j))
    
    return ans

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

print("Original matrix:")
for row in [[1, 0, 0], [1, 1, 1], [1, 0, 1]]:
    print(row)

result = solve(matrix)
print(f"\nLargest submatrix area: {result}")
Original matrix:
[1, 0, 0]
[1, 1, 1]
[1, 0, 1]

Largest submatrix area: 4

How It Works

The algorithm works in two phases:

  1. Height Calculation: For each cell containing 1, calculate the height of consecutive 1s ending at that position
  2. Area Maximization: For each row, sort the heights and calculate the maximum possible area by treating each height as the minimum height of a rectangle

After sorting each row, row[j] * (m - j) gives the area of rectangle with height row[j] and width (m - j).

Example Walkthrough

def solve_with_steps(matrix):
    n, m = len(matrix), len(matrix[0])
    print("Step 1: Calculate consecutive heights")
    
    # Create a copy to show original
    original = [row[:] for row in matrix]
    
    for i in range(1, n):
        for j in range(m):
            if matrix[i][j]:
                matrix[i][j] += matrix[i-1][j]
    
    print("After height calculation:")
    for row in matrix:
        print(row)
    
    print("\nStep 2: Process each row")
    ans = 0
    
    for i, row in enumerate(matrix):
        original_row = row[:]
        row.sort()
        print(f"Row {i}: {original_row} ? sorted: {row}")
        
        for j in range(m-1, -1, -1):
            area = row[j] * (m - j)
            ans = max(ans, area)
            print(f"  Height {row[j]} × Width {m-j} = Area {area}")
    
    return ans

# Test with step-by-step output
matrix = [
    [1, 0, 0],
    [1, 1, 1],
    [1, 0, 1]
]

result = solve_with_steps(matrix)
print(f"\nMaximum area: {result}")
Step 1: Calculate consecutive heights
After height calculation:
[1, 0, 0]
[2, 1, 1]
[3, 0, 2]

Step 2: Process each row
Row 0: [1, 0, 0] ? sorted: [0, 0, 1]
  Height 1 × Width 1 = Area 1
  Height 0 × Width 2 = Area 0
  Height 0 × Width 3 = Area 0
Row 1: [2, 1, 1] ? sorted: [1, 1, 2]
  Height 2 × Width 1 = Area 2
  Height 1 × Width 2 = Area 2
  Height 1 × Width 3 = Area 3
Row 2: [3, 0, 2] ? sorted: [0, 2, 3]
  Height 3 × Width 1 = Area 3
  Height 2 × Width 2 = Area 4
  Height 0 × Width 3 = Area 0

Maximum area: 4

Conclusion

This algorithm efficiently finds the largest submatrix area by first calculating consecutive heights, then using column rearrangement to maximize the area. The time complexity is O(n×m×log(m)) due to sorting each row.

Updated on: 2026-03-26T17:33:04+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements