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.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • -100 โ‰ค nums[i] โ‰ค 100
  • Follow-up: Can you solve this in O(n log n) time?

Visualization

Tap to expand
๐ŸŽช Concert Line OrganizationInitial State: Unsorted ArrayPerson1Person1Person2Person2Person2Person3Each person has a number (their value) and bought some ticketsStep 1: Count Tickets (Build Frequency Map)Person 1: 2 ticketsPerson 2: 3 ticketsPerson 3: 1 ticketSurvey complete! Now we know everyone's ticket count.Step 2: Organize Line (Sort by Rules)Rule 1: Fewer tickets = closer to frontRule 2: Same tickets = higher person number goes firstFinal Organized Line:Person31 ticketPerson12 ticketsPerson12 ticketsPerson23 ticketsPerson23 ticketsPerson23 ticketsPerfect! Organized by ticket count, then by person number
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).
Asked in
Amazon 15 Facebook 12 Apple 8 Google 6
87.5K Views
Medium Frequency
~15 min Avg. Time
2.9K 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