Skip to main content
Back to LeetCode Archive
Jul 23, 20243 min read

1636. Sort Array by Increasing Frequency (23 July 2024)

ArraySortingHash Table

Problem Description

Given an array of integers nums, your task is to sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in descending order.

You can find the problem statement on LeetCode.

Solution Explanation

To solve this problem, we need to sort the nums array based on the frequency of each element. Here's a step-by-step explanation of how we can achieve this:

1. Use an Unordered Map to Count Frequencies

  • We use an unordered map where the key is the element from nums, and the value is the frequency of that element.

2. Count the Frequencies

  • Iterate through the nums array and populate the map with the frequency of each element.

3. Sort the Array

  • Sort the nums array using a custom comparator.
  • The custom comparator sorts elements primarily by their frequency in ascending order.
  • If two elements have the same frequency, they are sorted in descending order.

Here's the C++ code implementing this solution:

class Solution {
public:
    vector<int> frequencySort(vector<int>& nums) {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        unordered_map<int, int> freq;
        for (int num : nums) {
            freq[num]++;
        }
 
        sort(nums.begin(), nums.end(), [&](int a, int b) {
            return freq[a] != freq[b] ? freq[a] < freq[b] : a > b;
        });
 
        return nums;
    }
};

Frequency Counting and Sorting

  • Unordered Map (freq):
    • Used to store the frequency of each element in the array.
    • Provides O(1) average time complexity for insert and access operations.

Example

Consider the following input:

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

Step-by-Step Execution

  1. Count the frequencies of each element:

    freq after counting: {1: 2, 2: 3, 3: 1}
    
  2. Sort the array using the custom comparator:

    Resulting order: [3, 1, 1, 2, 2, 2]
    

Conclusion

The described method uses an unordered map to efficiently count the frequency of elements in the array. The custom comparator in the sort function ensures the elements are sorted by frequency in ascending order and by value in descending order when frequencies are the same. This solution is efficient and straightforward, making it a practical choice for solving the problem of sorting an array by increasing frequency.