#1636

Sort Array by Increasing Frequency

Easy
ArrayHash TableSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a frequency map to count occurrences and then sorts the unique numbers based on their frequency and value. This is efficient and leverages sorting effectively.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map to count occurrences of each number.
  2. 2Step 2: Create a list of unique numbers from the original array.
  3. 3Step 3: Sort the unique numbers using a custom comparator based on frequency and value.
  4. 4Step 4: Build the output array by repeating each number according to its frequency.
solution.py8 lines
1# Full working Python code
2from collections import Counter
3
4def frequencySort(nums):
5    freq = Counter(nums)
6    unique_nums = list(freq.keys())
7    unique_nums.sort(key=lambda x: (freq[x], -x))
8    return [num for num in unique_nums for _ in range(freq[num])]

Complexity note: The time complexity is O(n log n) due to the sorting step of the unique numbers. The space complexity is O(n) because we store the frequency map and the output array.

  • 1Counting frequencies is essential for sorting based on occurrences.
  • 2Custom sorting logic can handle multiple criteria (frequency and value).

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.