Sort Array by Increasing Frequency - Problem
You're given an array of integers and need to sort it in a unique way! Instead of sorting by value, you'll sort by frequency of occurrence.
The Rules:
- Sort elements by their frequency in ascending order (least frequent first)
- When elements have the same frequency, sort them by value in descending order (largest first)
Example: In [1,1,2,2,2,3], the number 3 appears once (frequency 1), 1 appears twice (frequency 2), and 2 appears three times (frequency 3). So the result would be [3,1,1,2,2,2].
This problem combines frequency counting with custom sorting - perfect for practicing hash tables and sorting algorithms!
Input & Output
example_1.py โ Basic Example
$
Input:
nums = [1,1,2,2,2,3]
โบ
Output:
[3,1,1,2,2,2]
๐ก Note:
Element 3 has frequency 1, elements 1 have frequency 2, and elements 2 have frequency 3. Sorting by increasing frequency: 3 first, then 1's, then 2's.
example_2.py โ Same Frequency
$
Input:
nums = [2,3,1,3,2]
โบ
Output:
[1,3,3,2,2]
๐ก Note:
Both 1 and 2 have frequency 1, but since 2 > 1, we put 2 after 1. Elements 3 have frequency 2, so they come last.
example_3.py โ All Same Frequency
$
Input:
nums = [-1,1,-6,4,5,-6,1,4,1]
โบ
Output:
[5,-1,4,4,-6,-6,1,1,1]
๐ก Note:
5 and -1 have frequency 1 (5 > -1), 4 and -6 have frequency 2 (4 > -6), and 1 has frequency 3.
Visualization
Tap to expand
Understanding the Visualization
1
Count Everyone's Tickets
Survey all attendees to count their tickets - this is like building our frequency map
2
Apply Sorting Rules
People with fewer tickets go first, but among those with same ticket count, higher VIP numbers go first
3
Arrange the Line
Use the ticket count information to efficiently sort everyone according to the rules
Key Takeaway
๐ฏ Key Insight: By counting frequencies first, we avoid recalculating them during every comparison, reducing time complexity from O(nยณ) to O(n log n).
Time & Space Complexity
Time Complexity
O(n log n)
O(n) to count frequencies + O(n log n) for sorting with O(1) comparisons
โก Linearithmic
Space Complexity
O(n)
Hash map to store frequency of unique elements (worst case O(n) unique elements)
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 100
- -100 โค nums[i] โค 100
- Follow-up: Can you solve this in O(n log n) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code