Largest Submatrix With Rearrangements — LeetCode 1727 Python Solution

MediumGreedyArrayMatrixSorting
Problem
#1727
Reading time
2 min

The problem

You are given a binary matrix matrix of size m x 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.

Example

Input
matrix = [[0,0,1],[1,1,1],[1,0,1]]
Output
4
Explanation
You can rearrange the columns as shown above.

Python solution

Python
class Solution:
    def largestSubmatrix(self, matrix: List[List[int]]) -> int:
        for i in range(1, len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j]:
                    matrix[i][j] = matrix[i - 1][j] + 1
        ans = 0
        for row in matrix:
            row.sort(reverse=True)
            for j, v in enumerate(row, 1):
                ans = max(ans, j * v)
        return ans

Complexity

MeasureComplexity
TimeO(m \times n \times \log n)
SpaceO(1) to O(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1727. Largest Submatrix With Rearrangements is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1727. Largest Submatrix With Rearrangements?
LeetCode 1727. Largest Submatrix With Rearrangements is rated Medium on LeetCode.
What topics does LeetCode 1727. Largest Submatrix With Rearrangements cover?
LeetCode 1727. Largest Submatrix With Rearrangements is tagged Greedy, Array, Matrix and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview