Top Songs of the Week

Medium · Heaps & Top-K · about 20 min

A music app logs every play as a song id in plays. Return the k most played song ids for the weekly chart.

Order the chart by number of plays, most first. Songs with the same number of plays are ordered by smaller id first. If fewer than k different songs were played, return all of them in that order.

  • k >= 0. Ids are whole numbers and may be negative.

Example: most_played([4, 4, 1, 2, 2, 2, 3], 2) → [2, 4] (song 2 has 3 plays, song 4 has 2)

Hints

  • Count the plays of each song first.
  • Each song has a key: its play count (bigger is better) and then its id (smaller is better).
  • A heap of size k on that key gives the top k without sorting every song. Never rely on the order a map stores its keys.

Learn the pattern first: the Heaps & Top-K lesson.

More Heaps & Top-K problems