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 RearrangementsOriginal Matrix101110Rearranged Matrix110101Maximum Submatrix1 1Area = 1 × 2 = 2RearrangeExtractMove columns to group 1s together and maximize rectangular areaResult: Maximum Area = 2
Understanding the Visualization
1
Input Matrix
Binary matrix with 1s and 0s that can be rearranged by columns
2
Rearrange Columns
Find optimal column order to maximize submatrix of 1s
3
Maximum Area
Calculate area of largest rectangular submatrix containing only 1s
Key Takeaway
🎯 Key Insight: Transform into histogram problem by calculating consecutive 1s heights, then use greedy column sorting to maximize rectangle area.
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