Skip to content

Commit 7802ca4

Browse files
committed
LC 347. Top K Frequent Elements (Bucket Sort)
1 parent 5c3f9aa commit 7802ca4

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

leetcode/top-k-frequent-elements.py

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
# - Heap (Priority Queue) - Bucket Sort - Counting - Quickselect
88

99
import timeit
10-
from collections import Counter
10+
from collections import Counter, defaultdict
1111
from typing import List
1212

1313

@@ -19,13 +19,54 @@
1919
#
2020
# Runtime 95 ms Beats 95.19%
2121
# Memory Usage 18.4 Beats 99.66%
22-
class Solution:
22+
class UseCounter:
2323
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
2424
return [x[0] for x in Counter(nums).most_common(k)]
2525

2626

27+
# Use bucket sorting, first get the frequency of items in the input,
28+
# then create an array of buckets and place each unique value in the
29+
# array indexed by its frequency. To create the result, iterate in
30+
# reverse over the array indexes and pop elements until the result has
31+
# grown to have k elements.
32+
#
33+
# Time complexity: O(n) - Sorting the dictionary by value.
34+
# Space complexity: O(n) - The size of the dictionary.
35+
#
36+
# Runtime 104 ms Beats 71.15%
37+
# Memory Usage 18.7 Beats 42.44%
38+
class BucketSort:
39+
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
40+
# Count the frequency of each element, same as Counter(nums).
41+
freq = defaultdict(int)
42+
for num in nums:
43+
freq[num] += 1
44+
# A bucket that holds elements indexed by their frequency.
45+
bucket = []
46+
for num, count in freq.items():
47+
# Expand bucket if needed.
48+
while count + 1 > len(bucket):
49+
bucket.append(None)
50+
# If empty add a list at the index.
51+
if not bucket[count]:
52+
bucket[count] = []
53+
# Append the value indexed by its frequency.
54+
bucket[count].append(num)
55+
# Create a result of size k.
56+
res, idx = [], len(bucket) - 1
57+
while len(res) < k:
58+
if bucket[idx]:
59+
res.append(bucket[idx].pop())
60+
else:
61+
idx -= 1
62+
return res
63+
64+
2765
def test():
28-
executors = [Solution]
66+
executors = [
67+
UseCounter,
68+
BucketSort,
69+
]
2970
tests = [
3071
[[1], 1, [1]],
3172
[[3, 0, 1, 0], 1, [0]],

0 commit comments

Comments
 (0)