medium Largest Submatrix With Rearrangements
Problem Statement
You are given a binary matrix matrix of size m x n. You are allowed to shuffle the columns of the matrix in any order.
Return the area of the largest submatrix, whose all elements are 1 after shuffling the columns of the matrix.
Examples
Example 1:
- Input:
[[1,0,1],
[1,1,1],
[1,0,1]]
- Expected Output:
6
- Justification: By swapping the 2nd and 3rd columns, we can form a 2x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.
Example 2:
- Input:
[[0,1],
[1,1]]
- Expected Output:
2
- Justification: The columns can be rearranged (although in this case, it's not necessary) to form the largest rectangle of 1s that is 1x2 or 2x1. The area is 2.
Example 3:
- Input:
[[1,1,0,0],
[1,0,1,1],
[1,1,1,1],
[0,1,1,0]]
- Expected Output:
6
- Justification: By swapping the 2nd and 4th column, we can form a 3x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.
Try it yourself
Try solving this question here:
✅ Solution Largest Submatrix With Rearrangements
Problem Statement
You are given a binary matrix matrix of size m x n. You are allowed to shuffle the columns of the matrix in any order.
Return the area of the largest submatrix, whose all elements are 1 after shuffling the columns of the matrix.
Examples
Example 1:
- Input:
[[1,0,1],
[1,1,1],
[1,0,1]]
- Expected Output:
6
- Justification: By swapping the 2nd and 3rd columns, we can form a 2x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.
Example 2:
- Input:
[[0,1],
[1,1]]
- Expected Output:
2
- Justification: The columns can be rearranged (although in this case, it's not necessary) to form the largest rectangle of 1s that is 1x2 or 2x1. The area is 2.
Example 3:
- Input:
[[1,1,0,0],
[1,0,1,1],
[1,1,1,1],
[0,1,1,0]]
- Expected Output:
6
- Justification: By swapping the 2nd and 4th column, we can form a 3x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.
Solution
To solve this problem, the algorithm first focuses on converting the given binary matrix into a histogram representation. This conversion involves calculating the height of consecutive 1s in each column, essentially transforming the problem into finding the largest area under the histogram for each row. The rationale behind this approach is that by considering each row as the base and the calculated heights as the potential heights of rectangles, we can explore the maximum area that can be formed by rearranging these heights, thus rearranging columns.
After converting the matrix into a histogram of heights, the next step involves sorting the heights in each row in descending order. This sorting allows for the efficient calculation of the maximum area for each row by multiplying the height of each column by its rank in the sorted order. The reason this approach is effective is that it aligns with the principle of maximizing the area under the histogram by utilizing the tallest columns together, ensuring the formation of the largest possible rectangle of 1s. This method is believed to be the most efficient as it reduces the problem to a series of histogram area calculations, which can be done in linear time per row after sorting.
Step-by-step algorithm
- Step 1: Iterate through each cell of the matrix. For each cell that contains a 1, update its value to be the sum of itself and the value of the cell directly above it. This effectively calculates the height of consecutive 1s for each column.
- Step 2: For each row in the transformed matrix, sort the values in non-increasing order. This rearranges the columns in a way that aligns taller columns together, simulating the optimal rearrangement for forming the largest rectangle.
- Step 3: After sorting, iterate through each row's values. Multiply each value (height of the rectangle) by its index plus one (representing the width of the rectangle formed up to that column) to calculate the area of the rectangle that can be formed using that height.
- Step 4: Keep track of the maximum area encountered during the iteration through all rows.
- Step 5: Return the maximum area as the result.
Algorithm Walkthrough
Let's consider the input:
[[1,1,0,0],
[1,0,1,1],
[1,1,1,1],
[0,1,1,0]]
-
Step 1: Convert to Heights Matrix
- Starting from the second row, add the value of the current cell to the value above it if the current cell is 1. This computes the height of consecutive 1s for each column.
- After processing, the matrix becomes:
1 1 0 0 2 0 1 1 3 1 2 2 0 2 3 0 - Explanation: Each column now shows how many consecutive 1s are above, including the current cell.
-
Step 2: Sort Each Row in Non-Increasing Order
- Sort the heights within each row to bring the highest potential for forming large rectangles to the forefront.
- The matrix after sorting each row:
1 1 0 0 2 1 1 0 3 2 2 1 3 2 0 0 - Explanation: By sorting, we align columns in a way that maximizes the potential area for each row's histogram.
-
Step 3: Calculate the Maximum Area for Each Row
- For each row, calculate the area by multiplying each sorted height by its 1-based index (which represents the width of the rectangle that can be formed using that height).
- For the third row (
3 2 2 1), the areas calculated are3*1=3,2*2=4,2*3=6,1*4=4. The maximum area from this row is 6. - Perform this calculation for every row and track the overall maximum area.
-
Step 4: Identify the Maximum Area
- After evaluating all rows, the maximum area found is 6, which is the answer for this example.
-
Final Output:
- The algorithm concludes that the largest submatrix with rearrangements for the given example is 6.
Code
import java.util.Arrays;
public class Solution {
public int largestSubmatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
// Step 1: Convert to heights matrix
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 1) matrix[i][j] += matrix[i - 1][j];
}
}
int maxArea = 0;
// Step 2 & 3: Sort each row and calculate max area
for (int[] row : matrix) {
Arrays.sort(row);
for (int j = n - 1; j >= 0; j--) {
int width = n - j;
maxArea = Math.max(maxArea, row[j] * width);
}
}
return maxArea;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(
solution.largestSubmatrix(
new int[][] { { 1, 0, 1 }, { 1, 1, 1 }, { 1, 0, 1 } }
)
);
// Example 2
System.out.println(
solution.largestSubmatrix(new int[][] { { 0, 1 }, { 1, 1 } })
);
// Example 3
System.out.println(
solution.largestSubmatrix(
new int[][] {
{ 1, 1, 0, 0 },
{ 1, 0, 1, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 0 },
}
)
);
}
}
Complexity Analysis
Time Complexity: The overall time complexity of the algorithm is
Space Complexity: The space complexity of the algorithm is
🤖 Don't fully get this? Learn it with Claude
Stuck on Largest Submatrix With Rearrangements? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Largest Submatrix With Rearrangements** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Largest Submatrix With Rearrangements** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Largest Submatrix With Rearrangements**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Largest Submatrix With Rearrangements**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.