Sort Array by Frequency

Easy~10 min

Given an array of integers nums, sort the elements by their frequency in descending order (most frequent first).

If two elements have the same frequency, maintain their original relative order from the input array (stable sort).

Return the sorted array.

Examples

Example 1
Input: nums = [2, 3, 1, 3, 2]
Output: [2, 2, 3, 3, 1]
Explanation: 2 and 3 both appear twice, but 2 appears first in the original array. 1 appears once and goes last.
Example 2
Input: nums = [5, 5, 4, 6, 4, 4]
Output: [4, 4, 4, 5, 5, 6]
Explanation: 4 appears 3 times, 5 appears 2 times, 6 appears 1 time.
Example 3
Input: nums = [1]
Output: [1]
Explanation: Single element array is already sorted.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^5 <= nums[i] <= 10^5
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run