class Solution:
def kWeakestRows(self, mat, k):
# Count soldiers in each row (sum of 1s)
row_strength = [(sum(row), idx) for idx, row in enumerate(mat)]
# Sort by number of soldiers, then by row index
row_strength.sort()
# Return indices of the k weakest rows
return [idx for _, idx in row_strength[:k]]
class Solution {
public:
vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
vector<pair<int, int>> strength;
for (int i = 0; i < mat.size(); ++i) {
int soldiers = accumulate(mat[i].begin(), mat[i].end(), 0);
strength.push_back({soldiers, i});
}
sort(strength.begin(), strength.end());
vector<int> result;
for (int i = 0; i < k; ++i) {
result.push_back(strength[i].second);
}
return result;
}
};
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
int m = mat.length;
int[][] strength = new int[m][2];
for (int i = 0; i < m; i++) {
int soldiers = 0;
for (int val : mat[i]) soldiers += val;
strength[i][0] = soldiers;
strength[i][1] = i;
}
Arrays.sort(strength, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = strength[i][1];
}
return result;
}
}
var kWeakestRows = function(mat, k) {
let strength = mat.map((row, idx) => [row.reduce((a, b) => a + b, 0), idx]);
strength.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
return strength.slice(0, k).map(pair => pair[1]);
};
mat
with m
rows and n
columns, where each row represents soldiers (1
) followed by civilians (0
), the task is to find the indices of the k
weakest rows in the matrix. The "weakness" of a row is defined by the number of soldiers in it. If two rows have the same number of soldiers, the row with the lower index is considered weaker. The output should be a list of k
row indices, sorted from weakest to strongest.
1
s in each row gives us the strength of that row. The brute-force approach would be to count soldiers in every row, sort all rows by their soldier count (and row index for ties), and return the indices of the first k
rows. If we want to optimize, we could use a priority queue to keep track of the k
weakest rows as we process each one, but since the constraints are reasonable, sorting is simple and efficient enough.
mat
, count the number of soldiers (1
s). Since all 1
s come before 0
s, this can be done by summing the row.k
pairs from the sorted list. These represent the k
weakest rows.mat = [[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]]
k = 3
[(2,0), (4,1), (1,2), (2,3), (5,4)]
[(1,2), (2,0), (2,3), (4,1), (5,4)]
[2,0,3]
[2, 0, 3]
.