Delete Greatest Value in Each Row — LeetCode 2500 Python Solution

EasyArrayMatrixSortingSimulationHeap (Priority Queue)
Problem
#2500
Reading time
2 min

The problem

You are given an m x n matrix grid consisting of positive integers. Perform the following operation until grid becomes empty: Delete the element with the greatest value from each row.

Example

Input
grid = [[1,2,4],[3,3,1]]
Output
8
Explanation
The diagram above shows the removed values in each step.

Python solution

Python
class Solution:
    def deleteGreatestValue(self, grid: List[List[int]]) -> int:
        for row in grid:
            row.sort()
        return sum(max(col) for col in zip(*grid))

Complexity

MeasureComplexity
TimeO(m \times n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2500. Delete Greatest Value in Each Row is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2500. Delete Greatest Value in Each Row?
LeetCode 2500. Delete Greatest Value in Each Row is rated Easy on LeetCode.
What is the time complexity of LeetCode 2500. Delete Greatest Value in Each Row?
The Python solution on this page runs in O(m \times n \times \log n).
What is the space complexity of LeetCode 2500. Delete Greatest Value in Each Row?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 2500. Delete Greatest Value in Each Row cover?
LeetCode 2500. Delete Greatest Value in Each Row is tagged Array, Matrix, Sorting, Simulation and Heap (Priority Queue) 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