#1337

The K Weakest Rows in a Matrix

Easy
ArrayBinary SearchSortingHeap (Priority Queue)MatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

In the optimal approach, we can use a more efficient counting method combined with sorting. Since the soldiers are always on the left, we can use binary search to count them, making the solution faster.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize an empty list to store the count of soldiers and their respective row indices.
  2. 2Step 2: For each row, use binary search to find the number of soldiers (1's) in the row.
  3. 3Step 3: Store the count along with the row index in the list.
  4. 4Step 4: Sort the list based on the number of soldiers and then by row index.
  5. 5Step 5: Extract the first k indices from the sorted list and return them.
solution.py23 lines
1# Full working Python code
2mat = [[1,1,0,0,0], [1,1,1,1,0], [1,0,0,0,0], [1,1,0,0,0], [1,1,1,1,1]]
3k = 3
4
5def kWeakestRows(mat, k):
6    soldiers = []
7    for i in range(len(mat)):
8        count = binarySearch(mat[i])
9        soldiers.append((count, i))
10    soldiers.sort()  # Sort by count and then by index
11    return [soldiers[i][1] for i in range(k)]
12
13def binarySearch(row):
14    left, right = 0, len(row)
15    while left < right:
16        mid = (left + right) // 2
17        if row[mid] == 1:
18            left = mid + 1
19        else:
20            right = mid
21    return left
22
23print(kWeakestRows(mat, k))

Complexity note: The time complexity is O(n log n) due to sorting the soldiers array, while the binary search for counting soldiers is O(log n) for each row. The space complexity remains O(n) for storing the counts and indices.

  • 1The soldiers are always positioned to the left, allowing for efficient counting.
  • 2Sorting is essential for determining the weakest rows based on multiple criteria.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.