Frequency-Based Sorting - Problem

Given an array of integers, sort the elements based on their frequency of occurrence. Elements with higher frequency should appear first in the result.

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

Return the sorted array as the result.

Input & Output

Example 1 — Basic Frequency Sorting
$ Input: nums = [1,1,2,2,3]
Output: [1,1,2,2,3]
💡 Note: Elements 1 and 2 both appear 2 times, element 3 appears 1 time. Since 1 and 2 have same frequency, maintain original order where 1 comes first.
Example 2 — Clear Frequency Difference
$ Input: nums = [2,3,1,3,2]
Output: [2,2,3,3,1]
💡 Note: Element 2 appears 2 times (first at index 0), element 3 appears 2 times (first at index 1), element 1 appears 1 time. Result: 2s first, then 3s, then 1.
Example 3 — All Same Frequency
$ Input: nums = [1,2,3]
Output: [1,2,3]
💡 Note: All elements appear exactly once, so maintain the original order from the input array.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
INPUTOriginal Array11223Elements:1 appears 2 times2 appears 2 times3 appears 1 timeALGORITHM1. Count FrequenciesBuild hash map: {1:2, 2:2, 3:1}2. Sort by FrequencyOrder: freq 2 (1,2), then freq 1 (3)3. Maintain Stable OrderSame freq: keep original order4. Build Result ArrayExpand: [1,1,2,2,3]RESULTFrequency-Sorted Array11223[1,1,2,2,3]✓ Higher frequencies first✓ Stable ordering maintainedKey Insight:Count frequencies in a hash map first, then sort unique elements by frequencywhile maintaining the relative order of elements with equal frequencies.TutorialsPoint - Frequency-Based Sorting | Optimized Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen