Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 2 Updated

Frequency Sort

Counter + max-heap; pop most-frequent, emit `cnt` copies, repeat.

  • Full 5m
  • Revision
  • Flow

Problem Statement

Sort the elements of an array by frequency in descending order. Elements with higher frequency come first. For equal frequencies, any stable tie-break is acceptable unless otherwise specified.

Input

An integer array nums.

Example input
nums = [1, 1, 2, 2, 2, 3]

Output

The elements reordered so higher-frequency values come first.

Expected output
[2, 2, 2, 1, 1, 3]
 
// freq: 2→3, 1→2, 3→1
// emit 2's first, then 1's, then 3

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • Values may be any integer (works identically for strings — LeetCode 451 variant).

Intuition

Count frequencies, then repeatedly pull the most frequent element and emit that many copies. “Most frequent at top” = max-heap keyed on frequency. Unlike Top-K, we don’t cap the heap — we need all elements in output order.

Walkthrough — nums=[1,1,2,2,2,3]
freq:  {1:2, 2:3, 3:1}
heap (max by count):  [(3,2), (2,1), (1,3)]
 
pop (3,2) → emit [2,2,2]   result = [2,2,2]
pop (2,1) → emit [1,1]     result = [2,2,2,1,1]
pop (1,3) → emit [3]       result = [2,2,2,1,1,3] ✓

Solution

frequency_sort.py
import heapq
from collections import Counter
 
def frequencySort(nums: list[int]) -> list[int]:
    freq = Counter(nums)
    max_heap = [(-cnt, val) for val, cnt in freq.items()]   # negate → max-heap
    heapq.heapify(max_heap)                                  # O(u)
 
    result: list[int] = []
    while max_heap:
        neg_cnt, val = heapq.heappop(max_heap)
        result.extend([val] * (-neg_cnt))
    return result

Complexity

MetricValueReason
TimeO(n log u)Where u is distinct-value count. Each of u heap ops is log u, and total output-building work is O(n). Worst case O(n log n) when all elements are distinct.
SpaceO(n)Map + heap together, both bounded by u ≤ n. Output is also O(n).

Edge Case Thinking

ScenarioHandling
All distinctEvery element appears once; order among them is unspecified. Use a secondary sort key if determinism matters.
All identicalHeap has one entry; output is a full copy of the input.
Strings instead of intsWorks identically — swap the map type (LC 451 “Sort Characters By Frequency”).
Stability requirementHeap is not stable; include an insertion index as tie-breaker: (-cnt, idx, val).
Empty inputFrequency map empty, heap empty, return [].

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.