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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code