Given a binary matrix grid (a list of rows, each a list of 0/1), return the list of row indices ordered by the number of ones in the row, fewest first. Rows with the same number of ones are ordered by their index, smallest first.
Examples
Input: grid = [[1, 1, 0], [1, 0, 0], [1, 1, 1], [0, 0, 0]]
Output: [3, 1, 0, 2]
Explanation: Row 3 has 0 ones, row 1 has 1, row 0 has 2, row 2 has 3.
Input: grid = [[1, 0], [0, 1], [1, 1]]
Output: [0, 1, 2]
Explanation: Rows 0 and 1 both have one 1; the lower index comes first.
Constraints
0 <= len(grid) <= 5000, every row has the same length0 <= m <= 50- Target complexity: O(n * m + n log n).
Goals
- Compute a derived value per row and sort by it
- Break ties with the original index
- Return indices rather than the rows themselves