Skip to content
RED SAG Skills

Sort by Popularity

Sort the values in nums so that more frequent values come first. Values with the same frequency are ordered by value, smallest first. Equal values stay grouped together.

Return the sorted array.

Example 1

Input: nums = [4, 6, 2, 6, 4, 4]
Output: [4, 4, 4, 6, 6, 2]

Example 2

Input: nums = [3, 1, 2]
Output: [1, 2, 3]

Constraints

  • 0 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5
Hint 1

Count each value first.

Hint 2

Sort with a comparator on (frequency descending, value ascending).

Discussion 0

Join free to post in the discussion.

Good practice for: Data Scientist, Data Engineer, Machine Learning Engineer, AI Engineer (LLM & Generative AI), Backend Developer, Frontend Developer

Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.