#451

Sort Characters By Frequency

Medium Count + bucket

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rearrange a string so characters appear in decreasing order of frequency (equal characters grouped together).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: order letters by how often they appear, most first.

Why this works: count, then put letters into buckets by count and read buckets from high to low.

Example: "tree"

e:2, t:1, r:1→ "eetr" (or "eert")

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting a Character[] with a comparator on the fly — works, but O(n log n) and easy to get the tie handling wrong.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Strings
🎬 Episodes 16–20: video coming soon