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