↓Skip to main content
  1. LeetCode/

LeetCode 347: Top K Frequent Elements

·1 min· ·
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-27

  • Submissions: Runtime Error → Accepted ×2

Approach
#

Count with a Counter, then take the k most frequent:

  • A size-k min-heap keyed by count (Heap Template 1), O(n log k).
  • Bucket sort (Bucket Sort): counts are at most n, so bucket[c] holds the values with count c; collect from the largest bucket down until k values, O(n).

My Attempts
#

Attempt 1 called Counter(nums).most_common().keys(), but most_common() returns a list (AttributeError). [x for x, _ in Counter(nums).most_common(k)] passed, in O(n log n).

Solution
#

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = Counter(nums)
        buckets = [[] for _ in range(len(nums) + 1)]
        for x, c in cnt.items():
            buckets[c].append(x)
        res = []
        for c in range(len(nums), 0, -1):
            res += buckets[c]
            if len(res) >= k:
                return res[:k]
        return res

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • most_common() returns a list, which has no .keys().
  • The follow-up asks for better than O(n log n), so full sorting misses it.

Interview Explanation
#

I count, put each value into the bucket for its count (at most n buckets), and collect from the highest bucket down until k values. Time O(n); a size-k heap gives O(n log k).

Related

LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)
LeetCode 75: Sort Colors
·2 mins
LeetCode Medium Array Two-Pointers Sorting Quicksort
LeetCode 75 note: the Dutch flag, with 0s left of low and 2s right of high; after swapping a 2 to high, do not advance, since the swapped-in value is unchecked
LeetCode 73: Set Matrix Zeroes
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 note: record which rows and columns contain a 0 first, then update afterward; the follow-up uses the first row and column as markers
LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused