NewThe Learning module is now liveSee what's new

(This question is a variation of the LeetCode question 1366. Rank Teams by Votes. If you haven't completed that question yet, it is recommended to solve it first.)

A music streaming platform wants to rank its songs by popularity based on user preference data. Given n users and m songs, each user i provides a preference list pref[i], which is a permutation of song ids 0 to m - 1. If a < b, user i prefers song pref[i][a] over song pref[i][b].

  • Song x is said to beat song y if more than half of the users prefer x over y, or exactly half prefer x over y and x has a smaller ID than y.
  • Song x is considered more popular than song y if x has a higher beat count than y. If two songs beat the same number of songs, the one with the smaller ID is ranked higher.

Return the song ids sorted from most popular to least popular.

Constraints:

  • n == pref.length
  • m == pref[i].length for every valid i
  • 1 ≤ n, m ≤ 400

Example 1:

Input: pref = [[0, 1, 2], [0, 2, 1], [1, 2, 0]] Output: [0, 1, 2] Explanation: With 3 users and 3 songs, the pairwise comparisons are:

  • Song 0 vs Song 1: preferred by users 0 and 1 (2 out of 3) → Song 0 beats Song 1
  • Song 0 vs Song 2: preferred by users 0 and 1 (2 out of 3) → Song 0 beats Song 2
  • Song 1 vs Song 2: preferred by users 0 and 2 (2 out of 3) → Song 1 beats Song 2

Beat counts: Song 0 = 2, Song 1 = 1, Song 2 = 0, giving the ranking [0, 1, 2].

Example 2:

Input: pref = [[0], [0]] Output: [0]

Example 3:

Input: pref = [[4, 1, 3, 0, 2]] Output: [4, 1, 3, 0, 2]


Accepted
41/92
Acceptance Rate44.6%
Test Cases
Input
pref =
Output
Expected