Largest Submatrix With Rearrangements - Problem

You are given a binary matrix matrix of size m × n, and you are allowed to rearrange the columns of the matrix in any order.

Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.

A submatrix is a contiguous rectangular area within the matrix. The area is calculated as width × height.

Input & Output

Example 1 — Basic Rearrangement
$ Input: matrix = [[1,0,1],[1,1,0]]
Output: 2
💡 Note: Rearrange columns to [[1,1,0],[1,0,1]] or similar. The largest submatrix of 1s has area 2 (either 2×1 or 1×2).
Example 2 — Larger Matrix
$ Input: matrix = [[1,1,0],[1,0,1],[0,1,1]]
Output: 2
💡 Note: After optimal rearrangement, we can get a 2×1 or 1×2 submatrix of all 1s.
Example 3 — All Zeros
$ Input: matrix = [[0,0],[0,0]]
Output: 0
💡 Note: No 1s in the matrix, so the largest submatrix of 1s has area 0.

Constraints

  • 1 ≤ m, n ≤ 105
  • 1 ≤ m × n ≤ 105
  • matrix[i][j] is 0 or 1

Visualization

Tap to expand
Largest Submatrix With Rearrangements INPUT Binary Matrix (2x3) 1 0 1 1 1 0 col0 col1 col2 r0 r1 matrix = [ [1, 0, 1], [1, 1, 0] ] = 1 = 0 Goal: Find max area of 1s after column rearrangement ALGORITHM STEPS 1 Compute Heights Count consecutive 1s above 1 0 1 2 1 0 heights 2 Sort Each Row Descending order (greedy) 1 1 0 2 1 0 sorted 3 Calculate Areas area = height * (j+1) 4 Track Maximum Row1: 2*1=2, 1*2=2 Max area = 2 h[0]*1 = 2*1 = 2 h[1]*2 = 1*2 = 2 FINAL RESULT Optimal Column Order 1 1 0 1 0 1 2x1 = 2 Alternative: 1x2 submatrix 1 1 0 1x2 = 2 (same) OUTPUT 2 OK - Maximum Area Found Key Insight: By computing heights (consecutive 1s from top) for each cell, we transform the problem into finding the largest rectangle in a histogram. Sorting each row in descending order ensures taller bars are placed first, maximizing area = height[j] * (j+1). Time: O(m*n*log n). TutorialsPoint - Largest Submatrix With Rearrangements | Greedy - Row by Row Heights
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen