Python 1337.py
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
indices = [ [ i, sum(mat[i]) ] for i in range(len(mat)) ]
indices.sort(key = lambda x : x[1])
return [ i[0] for i in indices ][:k]
Difficulty
and has an acceptance rate of about 74% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Heap (Priority Queue)
- Matrix
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method kWeakestRows that receives a binary matrix mat and an integer k. Each row of the matrix represents soldiers (value 1) followed by civilians (value 0). The method returns the indices of the k rows that contain the fewest soldiers, ordered from weakest to strongest. The implementation follows a straightforward three-phase approach: compute a strength metric for each row, sort rows by that metric, and extract the first k indices.
Key Steps
Building the index-strength pairs
indices = [ [ i, sum(mat[i]) ] for i in range(len(mat)) ]
In this comprehension the code iterates over every row index i. For each row it calculates the total number of soldiers by applying sum to the row list, which works because the matrix contains only 0s and 1s. The result is a two-element list where the first element is the original row index and the second element is the soldier count. The collection indices therefore holds a parallel representation of row positions and their strengths.
Sorting rows by soldier count
indices.sort(key = lambda x : x[1])
The list.sort method is invoked with a key function that extracts the soldier count (x[1]) from each pair. This causes the entire indices list to be reordered in ascending order of strength. Because Python’s sort is stable, rows that share the same soldier count retain their original relative order, which aligns with the requirement to break ties by lower index.
Selecting the weakest rows
return [ i[0] for i in indices ][:k]
A second list comprehension extracts only the row indices (i[0]) from the sorted pairs. The resulting list is then sliced to keep only the first k elements, delivering exactly the required number of weakest rows.
Edge Cases Handled
When the input matrix is empty, len(mat) evaluates to zero, producing an empty indices list. The subsequent sort and slice operations act on an empty list, and the method returns an empty list, which is a sensible result for any k.
Rows that contain no soldiers consist entirely of zeros; sum(mat[i]) correctly yields zero, placing such rows at the front of the sorted order. Conversely, rows that are fully populated with soldiers produce a sum equal to the row length, ensuring they appear at the end of the ordering.
If k exceeds the number of rows, the slice operation [:k] simply returns all available indices without raising an error, gracefully handling oversized requests.
The stability of the sorting algorithm guarantees that rows with identical soldier counts are ordered by their original indices, satisfying the tie-breaking rule without additional logic.
Performance Optimizations
The use of the built-in sum function leverages a highly optimized C implementation for aggregating the binary values of each row, avoiding explicit loops in Python.
Constructing the indices list with a list comprehension creates the entire collection in a single pass, minimizing overhead compared to incremental appends.
Sorting with a key function that accesses a pre-computed integer (x[1]) avoids repeated calculations during comparison, allowing the sort routine to operate on simple integer keys.
Finally, the extraction of the result via a list comprehension combined with slicing performs both selection and truncation in a compact, memory-efficient manner, eliminating the need for intermediate structures.
ELI5 - Simplified Explanation
Imagine a big grid full of ones and zeros, like a checkerboard with some spots filled in. Each row in this grid is a team of soldiers, and the ones represent people who know how to march. The goal is to figure out which teams have the fewest soldiers.
First, the computer looks at every single row one by one and counts how many ones are in each row. It keeps a little notebook where it writes down the number of the row and the count of soldiers standing there.
Next, the computer uses its sorting power to put the rows in order based on those counts. It puts the teams with the smallest number of soldiers right at the front of the line, just like lining up for snack time from shortest to tallest.
Finally, since there might be a lot of rows, the computer takes only the first few teams from the front of that line. The number of teams it picks is exactly the amount asked for at the very start. It ignores all the other teams and just points to the ones that have the fewest soldiers altogether.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Java | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| qiyuangong | Java | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 304: Range Sum Query 2D - Immutable
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality