Rank songs by pairwise user preferences
ConfluentSoftware Engineer · Online AssessmentLast updated
This question evaluates the ability to aggregate pairwise user preferences, implement majority-based comparison rules with deterministic tie-breakers, and compute a global ranking via beat counts.
You are given preference rankings for n users over m songs. Each song is labeled from 0 to m - 1.
For each user i (0-indexed), you are given an array pref[i] of length m that is a permutation of [0, 1, ..., m-1]. This array represents user i's ranking of all songs:
- If song
aappears before songbinpref[i], then useriprefers songaover songb.
Using these preference lists, define the following:
- Song x beats y:
- Let
count_pref_xbe the number of users who preferxovery. - Song
xbeats songyif either: count_pref_xis strictly greater than half of all users (i.e.,count_pref_x > n / 2), orcount_pref_xis exactly half of all users (i.e.,count_pref_x * 2 == n) andx < y(by song ID).
- Song x is more popular than y:
- For each song, define its beat count as the number of distinct other songs it beats according to rule (1).
- Song
xis more popular than songyif: - The beat count of
xis greater than the beat count ofy, or - The beat counts are equal and
x < y(by song ID).
Task: Given n, m, and all preference lists pref[0..n-1], compute the popularity ranking of all songs. Return a list of all song IDs from most popular to least popular, sorted by the "more popular than" relation defined above.
Assume:
1 <= m <= M_max,1 <= n <= N_max(choose reasonable constraints if implementing).- All
pref[i]are valid permutations of[0, ..., m-1].
Your function should output an array of length m containing the song IDs in descending order of popularity. Break ties using the song ID (smaller ID is considered more popular when beat counts are equal).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.