Program to sort array by increasing frequency of elements in Python

Suppose we have an array with some elements where elements may appear multiple times. We have to sort the array such that elements are sorted according to their increasing frequency. Elements that appear fewer times will come first, and when frequencies are equal, larger elements come first.

So, if the input is like nums = [1,5,3,1,3,1,2,5], then the output will be [2, 5, 5, 3, 3, 1, 1, 1]

Algorithm Steps

To solve this, we will follow these steps ?

  • Create a frequency map to count occurrences of each element

  • Group elements by their frequency

  • Sort frequencies in ascending order

  • For each frequency group, sort elements in descending order

  • Build the result by repeating each element according to its frequency

Method 1: Using Frequency Mapping

This approach uses a dictionary to group elements by their frequency ?

def solve(nums):
    mp = {}
    
    # Group elements by their frequency
    for i in set(nums):
        x = nums.count(i)
        if x in mp:
            mp[x].append(i)
        else:
            mp[x] = [i]
    
    ans = []
    
    # Sort by frequency (ascending), then by element value (descending)
    for frequency in sorted(mp):
        for element in sorted(mp[frequency], reverse=True):
            ans.extend([element] * frequency)
    
    return ans

nums = [1, 5, 3, 1, 3, 1, 2, 5]
result = solve(nums)
print("Input:", nums)
print("Output:", result)
Input: [1, 5, 3, 1, 3, 1, 2, 5]
Output: [2, 5, 5, 3, 3, 1, 1, 1]

Method 2: Using Counter and Custom Sorting

This approach uses Python's Counter for cleaner frequency counting ?

from collections import Counter

def solve_with_counter(nums):
    # Count frequency of each element
    freq = Counter(nums)
    
    # Sort elements by frequency (ascending), then by value (descending)
    sorted_elements = sorted(freq.keys(), key=lambda x: (freq[x], -x))
    
    result = []
    for element in sorted_elements:
        result.extend([element] * freq[element])
    
    return result

nums = [1, 5, 3, 1, 3, 1, 2, 5]
result = solve_with_counter(nums)
print("Input:", nums)
print("Output:", result)
Output: [2, 5, 5, 3, 3, 1, 1, 1]

How It Works

Let's trace through the example step by step ?

nums = [1, 5, 3, 1, 3, 1, 2, 5]

# Step 1: Count frequencies
from collections import Counter
freq = Counter(nums)
print("Frequencies:", dict(freq))

# Step 2: Group by frequency
freq_groups = {}
for element, count in freq.items():
    if count not in freq_groups:
        freq_groups[count] = []
    freq_groups[count].append(element)

print("Grouped by frequency:", freq_groups)

# Step 3: Sort and build result
for frequency in sorted(freq_groups.keys()):
    elements = sorted(freq_groups[frequency], reverse=True)
    print(f"Frequency {frequency}: {elements}")
Frequencies: {1: 3, 5: 2, 3: 2, 2: 1}
Grouped by frequency: {3: [1], 2: [5, 3], 1: [2]}
Frequency 1: [2]
Frequency 2: [5, 3]
Frequency 3: [1]

Comparison

Method Time Complexity Space Complexity Best For
Frequency Mapping O(n²) due to count() O(n) Simple understanding
Counter with Sorting O(n log n) O(n) Better performance

Conclusion

To sort an array by increasing frequency, group elements by their frequency count, then sort by frequency ascending and element value descending. The Counter approach is more efficient for larger datasets.

Updated on: 2026-03-25T20:24:33+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements