⚡Flashcard Drill➔
NeetCode #96LC-1636EasyArrays & Hashing
← Back to All Problems

#96 · #1636 · Sort Array by Increasing Frequency(按照频率将数组升序排序)

📌 Problem Statement & Constraints

Given an integer array nums, sort it in ascending order of frequency, breaking ties in descending order of value. Constraints: 1 <= nums.length <= 100, -100 <= nums[i] <= 100.

💡 Core Algorithmic Approaches

  1. Count the frequencies, then sort with a composite key.
  2. The key is (frequency ascending, value descending), which in Python is key=lambda x: (cnt[x], -x).
  3. Sorting the original array with that key keeps every duplicate adjacent and in the required order.
  4. Because -100 <= nums[i] <= 100, a counting array indexed by value plus 100 is a valid O(n + V) alternative.

💻 Benchmark Python3 Implementation

class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        from collections import Counter
        cnt = Counter(nums)
        return sorted(nums, key=lambda x: (cnt[x], -x))   # freq asc, value desc

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n): the sort dominates. A counting-array bucket approach would be O(n + V) with V = 201.
💾 Space Complexity
O(n) for the sorted copy plus O(k) for the counter.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the tie-break on value: the problem explicitly requires descending value order for equal frequencies.
  • Using key=lambda x: (cnt[x], x): this gives ascending value on ties, the opposite of the requirement.
  • Sorting the counter's items and expanding: workable, but sorting the original array is simpler and automatically emits the right number of copies.
⚡
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

中文速览与面试要点

按照频率将数组升序排序

给你一个整数数组 nums,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。请你返回排序后的数组。约束:1 ≤ nums.length ≤ 100;-100 ≤ nums[i] ≤ 100。

核心要点

  • 频次统计 + 自定义排序键(标准解) :用 Counter 统计频次,排序键为 (频次, -值) 。
  • 为什么第二关键字取负值 :Python 的 sorted 是升序排序,而题目要求频率相同时按值 降序 ,因此把值取负即可让较大的值排在前面。
  • 替代方案 :先按值降序排序,再用 sorted(..., key=频次) 做稳定排序,两步都是 O(n log n) 但代码更长。
  • 注意返回的是原数组的排列 :每个元素都要保留(包括重复),不是返回去重后的值。

常见陷阱

  • 排序键写成 (cnt[x], x) :这样频率相同时会按值 升序 ,与题目要求的降序相反。必须写成 -x 。
  • 对 Counter 的键排序后展开 :需要额外把每个值重复其频次次,比直接排序原数组更繁琐,且容易漏掉重复。
  • 误以为要去重 :返回的数组长度必须等于 nums 的长度,重复元素都要保留。

参考实现

from collections import Counter

class Solution:
    def frequencySort(self, nums: list[int]) -> list[int]:
        cnt = Counter(nums)
        # 频次升序;频次相同时值降序(故对值取负)
        return sorted(nums, key=lambda x: (cnt[x], -x))