Sponsored
Sponsored
In this approach, we directly count the number of soldiers in each row by iterating through the elements of the row, and then sort the rows based on the count followed by their index to determine the order.
Steps to implement:
Time Complexity: O(m*n + m*log m) due to counting and sorting the rows.
Space Complexity: O(m) to store the row strength information.
1from typing import List
2
3def kWeakestRows(mat: List[List[int]], k: int) -> List[int]:
4 row_strength = []
5 for index, row in enumerate(mat):
6 soldier_count = 0
7 for val in row:
8 if val == 1:
9 soldier_count += 1
10 else:
11 break
12 row_strength.append((soldier_count, index))
13 row_strength.sort()
14 return [index for _, index in row_strength[:k]]
In the Python solution, a list of tuples is created where each tuple stores the soldier count and the row index. This list is then sorted and the indices of the k weakest rows are extracted.
This approach uses binary search to efficiently count the number of soldiers in each row. Given that soldiers are always positioned before civilians, binary search can help quickly find the first civilian and thus the count of soldiers.
Implementation steps:
Time Complexity: O(m*log n + m*log m) due to binary search for counting and sorting rows.
Space Complexity: O(m), for maintaining strength array storage.
This solution optimizes soldier count using binary search in each row. This reduces the time complexity to efficiently find each row's strength before sorting and extracting indices.