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 =
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.
#include <algorithm>
using namespace std;
int countSoldiers(const vector<int>& row) {
int low = 0, high = row.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (row[mid] == 1) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low;
}
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int, int>> rowStrength;
for (int i = 0; i < mat.size(); ++i) {
int soldierCount = countSoldiers(mat[i]);
rowStrength.push_back({soldierCount, i});
}
sort(rowStrength.begin(), rowStrength.end());
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(rowStrength[i].second);
}
return result;
}
The C++ solution employs a helper function for binary search to count soldiers and then proceeds with the usual sorting and extraction of weakest row indices.