Search⌘ K
AI Features

Solution: The K Weakest Rows in a Matrix

Explore an algorithm to find the k weakest rows in a matrix where soldiers are represented by ones and civilians by zeros. Learn to apply binary search to count soldiers per row efficiently and use a max-heap to track and return the weakest rows in order, balancing time and space complexity.

Statement

You are given an m×nm \times n binary matrix of 11’s (representing soldiers) and 00’s (representing civilians). The soldiers are positioned in front of the civilians, i.e., all the 11’s will appear to the left of all the 00’s in each row.

A row ii is weaker than a row jj if any of the following is TRUE:

  • The number of soldiers in row ii is less than the number of soldiers in row jj.

  • Both rows have the ...