The K Weakest Rows in a Matrix — LeetCode 1337 Python Solution

EasyArrayBinary SearchMatrixSortingHeap (Priority Queue)
Problem
#1337
Reading time
2 min

The problem

You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians.

Example

Input
mat =
Output
[2,0,3]
Explanation
The number of soldiers in each row is:

Python solution

Python
class Solution:
    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
        m, n = len(mat), len(mat[0])
        ans = [n - bisect_right(row[::-1], 0) for row in mat]
        idx = list(range(m))
        idx.sort(key=lambda i: ans[i])
        return idx[:k]

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1337. The K Weakest Rows in a Matrix is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

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 1337. The K Weakest Rows in a Matrix?
LeetCode 1337. The K Weakest Rows in a Matrix is rated Easy on LeetCode.
What topics does LeetCode 1337. The K Weakest Rows in a Matrix cover?
LeetCode 1337. The K Weakest Rows in a Matrix is tagged Array, Binary Search, Matrix, Sorting 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