The K Weakest Rows in a Matrix - Problem
Imagine you're a military strategist analyzing the defensive strength of different battle formations. You have an m x n binary matrix representing a battlefield where 1's represent soldiers and 0's represent civilians.
The key insight is that soldiers always position themselves in front of civilians - meaning all 1's appear to the left of all 0's in each row.
Your mission: Identify the k weakest rows based on these rules:
- A row is weaker if it has fewer soldiers
- If two rows have the same number of soldiers, the one with the smaller index is weaker
Return the indices of the k weakest rows, ordered from weakest to strongest.
Example: If row 0 has 2 soldiers, row 1 has 1 soldier, and row 2 has 3 soldiers, and k=2, you'd return [1, 0] because row 1 is weakest (1 soldier), followed by row 0 (2 soldiers).
Input & Output
example_1.py — Basic Case
$
Input:
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
›
Output:
[2,0,3]
💡 Note:
Row 2 has 1 soldier (weakest), row 0 has 2 soldiers, row 3 has 2 soldiers (but comes after row 0), so the 3 weakest are [2,0,3]
example_2.py — Tie Breaking
$
Input:
mat = [[1,0,0,0],[1,1,1,1],[1,0,0,0],[1,0,0,0]], k = 2
›
Output:
[0,2]
💡 Note:
Rows 0, 2, 3 all have 1 soldier each. Since we need k=2 weakest and there's a tie, we pick the ones with smaller indices: [0,2]
example_3.py — All Different
$
Input:
mat = [[1,1,1],[1,1,0],[1,0,0]], k = 2
›
Output:
[2,1]
💡 Note:
Row 2 has 1 soldier (weakest), row 1 has 2 soldiers (second weakest), row 0 has 3 soldiers (strongest)
Constraints
-
m == mat.length -
n == mat[i].length -
2 ≤ n, m ≤ 100 -
1 ≤ k ≤ m -
matrix[i][j]is either 0 or 1 - All 1's appear before all 0's in each row (soldiers before civilians)
Visualization
Tap to expand
Understanding the Visualization
1
Count Soldiers
For each unit (row), count the number of soldiers
2
Rank by Strength
Determine which units are weakest based on soldier count
3
Handle Ties
When units have same strength, prioritize by unit number (index)
4
Select Top K
Choose the k weakest units for reinforcement
Key Takeaway
🎯 Key Insight: Since soldiers always position before civilians in each row, we can use binary search to find the soldier count in O(log n) time instead of scanning the entire row.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code