Sum in a Matrix — LeetCode 2679 Python Solution

MediumArrayMatrixSortingSimulationHeap (Priority Queue)
Problem
#2679
Reading time
2 min

The problem

You are given a 0-indexed 2D integer array nums. Initially, your score is 0.

Example

Input
nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]]
Output
15
Explanation
In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15.

Python solution

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

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2679. Sum in a Matrix 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 2679. Sum in a Matrix?
LeetCode 2679. Sum in a Matrix is rated Medium on LeetCode.
What is the time complexity of LeetCode 2679. Sum in a Matrix?
The Python solution on this page runs in O(n log n).
What is the space complexity of LeetCode 2679. Sum in a Matrix?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2679. Sum in a Matrix cover?
LeetCode 2679. Sum in a Matrix 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