Skip to the code
cf.
+25 XP

#19 Sort Tags by Popularity

medium

A blog stores each post's tag as a number id. To build a tag strip, you want the ids reordered so the most used tags come first.

Write sortByPopularity(tags) that returns a new array with the same numbers, ordered by how often each number appears (most often first). Numbers that appear equally often go in increasing order. Copies of the same number stay next to each other.

Example 1

Input: tags = [4,1,2,2,4,4,3]
Output: [4,4,4,2,2,1,3]

4 appears 3 times, 2 twice, and 1 and 3 once each (1 before 3).

Example 2

Input: tags = [5,-1,5,-1,0]
Output: [-1,-1,5,5,0]

-1 and 5 both appear twice, so the smaller one, -1, goes first.

Constraints

  • 0 <= tags.length <= 10^5
  • -10^4 <= tags[i] <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).