↓Skip to main content
  1. LeetCode/

LeetCode 1337: The K Weakest Rows in a Matrix

·1 min· ·
LeetCode Easy Array Binary-Search Sorting Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-21

  • Submissions: Accepted (first try)

Approach
#

Each row’s 1s precede its 0s, so the soldier count is the position of the first 0, found by binary search (Binary Search Template 1). Sort by (count, row index) and take the first k indices.

My Solution
#

class Solution:
    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
        def soldiers(row):
            l, r = 0, len(row)
            while l < r:
                mid = (l + r) // 2
                if row[mid] == 1:
                    l = mid + 1
                else:
                    r = mid
            return l
        return sorted(range(len(mat)), key=lambda i: (soldiers(mat[i]), i))[:k]

I originally used sum(row) and a heap, which also passes; here binary search uses the fact that the 1s come first.

Complexity
#

Time O(m log n + m log m), space O(m).

Mistakes to Avoid
#

  • With equal counts, the smaller row index is weaker.

Interview Explanation
#

Soldiers lead each row, so binary search finds the first 0 for the count; sorting by (count, index) gives the first k. Time O(m log n + m log m).

Related

LeetCode 506: Relative Ranks
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 506 note: sort indices by score descending, give medals to the top three and rank strings to the rest, writing back into the original positions
LeetCode 1464: Maximum Product of Two Elements in an Array
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 1464 note: all values are positive, so take the two largest a and b and return (a - 1)(b - 1)
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 1051: Height Checker
·1 min
LeetCode Easy Array Sorting Counting-Sort Bubble-Sort
LeetCode 1051 note: sort and count the positions that differ from the original
LeetCode 594: Longest Harmonious Subsequence
·1 min
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 note: subsequences need not be contiguous, so just count; for each x add the counts of x and x + 1
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them