Skip to content
BytePatterns

K Weakest Squads

EasyHeaps#top-k#max-heap~20m

Problem

A training roster is a grid of 0s and 1s where each row is a squad. In every row the 1s (trained members) all come before the 0s (recruits). Squad i is weaker than squad j when it has fewer 1s, or the same number of 1s and a smaller index. Return the indices of the k weakest squads, weakest first.

Examples

Input:  roster = [[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]
Why:    the counts are 2, 4, 1, 2 and 5, and the tie between squads 0 and 3 goes to the smaller index
Input:  roster = [[1, 0], [1, 0], [0, 0]], k = 2
Output: [2, 0]
Input:  roster = [[1, 1]], k = 1
Output: [0]
Why:    edge case, a single squad is the weakest by default

Hints

0 / 3

Stuck on the idea rather than the code? Top K Elements covers it.