⚡Flashcard Drill➔
NeetCode #148LC-451MediumArrays & Hashing
← Back to All Problems

#148 · #451 · Sort Characters By Frequency(根据字符出现频率排序)

📌 Problem Statement & Constraints

Given a string s, sort it in decreasing order of character frequency. Constraints: 1 <= s.length <= 5 * 10^5; s consists of ASCII characters.

💡 Core Algorithmic Approaches

  1. Count the frequency of every character.
  2. Sort the distinct characters by frequency descending.
  3. Emit each character repeated by its frequency.
  4. Because the alphabet is bounded, a bucket sort by frequency gives O(n) instead of O(k log k).

💻 Benchmark Python3 Implementation

class Solution:
    def frequencySort(self, s: str) -> str:
        from collections import Counter
        cnt = Counter(s)
        # sort distinct characters by frequency, descending
        return "".join(ch * cnt[ch] for ch in sorted(cnt, key=lambda c: -cnt[c]))


# Bucket-sort variant: O(n) since the maximum frequency is len(s)
class Solution2:
    def frequencySort(self, s: str) -> str:
        from collections import Counter
        cnt = Counter(s)
        buckets = [[] for _ in range(len(s) + 1)]
        for ch, c in cnt.items():
            buckets[c].append(ch)
        out = []
        for c in range(len(s), 0, -1):     # high frequency first
            for ch in buckets[c]:
                out.append(ch * c)
        return "".join(out)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n + k log k) for the sort-based version with k distinct characters, or O(n) for the bucket variant.
💾 Space Complexity
O(n) for the output plus O(k) for the counter.

⚠️ Interview Pitfalls & Follow-ups

  • Sorting the whole string by frequency: only the distinct characters need sorting, then the repetitions are emitted.
  • Sorting ascending: the problem asks for decreasing frequency.
  • Forgetting the multiplicity: ch * cnt[ch] must emit every copy, not one.
  • Assuming ties matter: the problem accepts any order among equal frequencies.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

根据字符出现频率排序

给定一个字符串 s,根据字符出现的 频率 对其进行 降序 排序。一个字符出现的频率是它出现在字符串中的次数。返回已排序的字符串。如果有多个答案,返回其中任何一个。约束:1 ≤ s.length ≤ 5 × 10^5;s 由大小写英文字母和数字组成。

核心要点

  • 计数 + 按频次降序拼接(标准解) :用 Counter 统计频次,按频次降序排列字符,再把每个字符重复其频次次拼接。
  • Counter.most_common() 的便利 :它按计数降序返回 (元素, 计数) 列表,且计数相同时保持插入顺序(Python 3.7+ 的有序性)。
  • 拼接方式 : "".join(c * v for c, v in cnt.most_common()) ,一行完成。
  • 复杂度 :统计 O(n),排序 O(k log k)(k 为不同字符数,本题 ≤ 62),拼接 O(n)。整体 O(n + k log k)。

常见陷阱

  • 返回去重后的字符串 :必须保留每个字符的全部重复(按频次重复),长度应与输入相同。
  • 用 sorted(s, key=cnt.get) 升序 :默认升序会得到频率 从低到高 的顺序,与题意相反。需要加 reverse=True 或对频次取负。
  • 拼接时忘记乘以频次 :只输出 c 会让结果长度远小于输入。
  • 担心并列时结果不确定 :题目允许返回任意一种答案,因此并列顺序无关。

参考实现

from collections import Counter

class Solution:
    def frequencySort(self, s: str) -> str:
        cnt = Counter(s)
        # most_common() 按计数降序返回 (字符, 计数)
        return ''.join(c * v for c, v in cnt.most_common())

# 显式排序版本(等价):
# return ''.join(sorted(s, key=lambda c: -cnt[c]))