You are given a matrix of integers. For each row, find the second most frequent number in that row.
Ties in frequency are broken by value. When several numbers share the highest frequency, the largest of them counts as the most frequent and the second largest of them counts as the second most frequent. If a row contains only one distinct number, the answer for that row is -1.
Return a list whose i-th element is the answer for row i.
Function Signature
def second_most_frequent(matrix: list[list[int]]) -> list[int]:
...
Rules
-
Rank the distinct values of a row by frequency, highest first. Two values with the same frequency are ordered by value, larger first. The answer for the row is the value in second place of this ranking. This also settles the case where one value has the top frequency and several values tie for the next one: the largest of those comes second.
-
Each row is counted on its own. Counts never carry over between rows.
-
Rows can have different lengths.
-
A row with a single distinct value gives
-1
. Values can be negative, so
-1
can also be a genuine second-place value, and the output does not tell the two cases apart.
Constraints
-
1 <= len(matrix) <= 100
-
1 <= len(matrix[i]) <= 100
-
-10^4 <= matrix[i][j] <= 10^4
Examples
Input: matrix = [[1,1,2,2,3],[4,4,4,5,5],[7,7,7,7,7]]
Output: [1,5,-1]
In row 0, both 1 and 2 appear twice, so the larger value 2 is the most frequent and 1 is second. Row 1 has 4 three times and 5 twice, and row 2 has only one distinct number.
Input: matrix = [[3,3,3,5,5,5,2,2,2],[10,20,30]]
Output: [3,20]
Every value in row 0 appears three times, so the ranking goes by value: 5, then 3, then 2. In row 1 every value appears once, so the ranking is 30, 20, 10.
Input: matrix = [[4,4,4,5,5,6,6],[0,0,-1]]
Output: [6,-1]
In row 0, 4 is the most frequent, and 5 and 6 tie for the next frequency, so the larger value 6 comes second. In row 1, 0 appears twice and -1 once, so -1 is a real second-place answer.