Sort Array by Increasing Frequency - Problem

Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.

Return the sorted array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
💡 Note: Frequencies: 1 appears 2 times, 2 appears 3 times, 3 appears 1 time. Sort by frequency: 3(1 time), 1(2 times), 2(3 times)
Example 2 — Same Frequencies
$ Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
💡 Note: Frequencies: 1→1, 2→2, 3→2. Same frequency elements (2,3) sorted by value descending: 3 before 2
Example 3 — All Different
$ Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
💡 Note: Frequencies: 5→1, -1→1, 4→2, -6→2, 1→3. Sort by frequency ascending, same frequency by value descending

Constraints

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

Visualization

Tap to expand
Sort Array by Increasing Frequency INPUT nums = [1,1,2,2,2,3] 1 1 2 2 2 3 0 1 2 3 4 5 Frequency Count: 1: 2x 2: 3x 3: 1x Colors indicate same values ALGORITHM (Hash) 1 Build Hash Map Count frequency of each num {1:2, 2:3, 3:1} 2 Create Pairs (value, frequency) tuples [(1,2),(2,3),(3,1)] 3 Custom Sort By freq ASC, val DESC freq: 1 < 2 < 3 same freq: val DESC 4 Build Result Expand by frequency [3,1,1,2,2,2] FINAL RESULT Sorted by Frequency: 3 1 1 2 2 2 1x 2x 3x Order Explanation: 3 appears 1x (lowest freq) 1 appears 2x (middle freq) 2 appears 3x (highest freq) Same freq: higher val first [3,1,1,2,2,2] Status: OK Key Insight: Use a hash map to count frequencies in O(n) time. Then sort with a custom comparator: primary key = frequency (ascending), secondary key = value (descending for ties). TutorialsPoint - Sort Array by Increasing Frequency | Hash Map Approach Time: O(n log n) | Space: O(n)
Asked in
Amazon 3 Apple 2
120.0K Views
Medium Frequency
~15 min Avg. Time
2.4K 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