Leetcode 1337: The K Weakest Rows in a Matrix

grid47
grid47
Exploring patterns and algorithms
Jun 26, 2024 5 min read

You are given a binary matrix where 1’s represent soldiers and 0’s represent civilians. The soldiers are positioned before the civilians in each row. A row is weaker than another if it has fewer soldiers, or if it has the same number of soldiers but appears earlier. Your task is to return the indices of the k weakest rows in the matrix, ordered from weakest to strongest.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary matrix mat of size m x n, followed by an integer k representing the number of weakest rows to return.
Example: mat = [[1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 1, 1, 1]], k = 2
Constraints:
• 2 <= n, m <= 100
• 1 <= k <= m
• matrix[i][j] is either 0 or 1.
Output: The output should be a list of integers representing the indices of the k weakest rows, ordered from weakest to strongest.
Example: For mat = [[1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 1, 1, 1]], k = 2, the output will be [2, 0].
Constraints:
• The number of rows to return is always valid (1 <= k <= m).
Goal: The goal is to identify the k weakest rows in the matrix and return them in the required order.
Steps:
• 1. Count the number of soldiers (1's) in each row.
• 2. Pair each row's soldier count with its index.
• 3. Sort these pairs first by soldier count, and if two rows have the same count, by their index.
• 4. Extract the indices of the k weakest rows and return them.
Goal: The constraints ensure that the matrix size is manageable for the solution approach, and that k is always within a valid range.
Steps:
• 2 <= n, m <= 100
• 1 <= k <= m
• matrix[i][j] is either 0 or 1.
Assumptions:
• The matrix rows contain only 0's and 1's, with 1's representing soldiers and 0's representing civilians.
• The number of soldiers in a row is always less than or equal to the number of columns.
Input: Example 1: mat = [[1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 0], [1, 1, 1, 1]], k = 2
Explanation: The weakest rows are rows 2 (1 soldier) and 0 (2 soldiers).

Input: Example 2: mat = [[1, 0], [1, 1], [1, 0], [1, 0]], k = 3
Explanation: The weakest rows are rows 0, 2, and 3 (each with 1 soldier), ordered by their indices.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus