Skip to content

Commit aeac041

Browse files
committed
feat: top-k-frequent-elements challenge
1 parent bb3ce1d commit aeac041

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Challenge: Given an array of numbers, create a function that returns the k elements that appear most frequently.
2+
# Consider using data structures like hash maps and heaps to efficiently manage frequency.
3+
# Provide two variants using OOP: one with hash map and sorting, and another with hash map and heap.
4+
5+
from top_k_hashmap import TopKFrequentHashMap
6+
from top_k_heap import TopKFrequentHeap
7+
8+
def main():
9+
nums = [1,1,1,2,2,3,3,3,3,4,4,5]
10+
k = 3
11+
12+
print("Using HashMap and Sorting:")
13+
top_k_hashmap = TopKFrequentHashMap(nums)
14+
print(top_k_hashmap.top_k_frequent(k))
15+
16+
print("Using HashMap and Heap:")
17+
top_k_heap = TopKFrequentHeap(nums)
18+
print(top_k_heap.top_k_frequent(k))
19+
20+
if __name__ == "__main__":
21+
main()
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import List
2+
from collections import Counter
3+
4+
class TopKFrequentHashMap:
5+
def __init__(self, nums: List[int]):
6+
self.nums = nums
7+
8+
def top_k_frequent(self, k: int) -> List[int]:
9+
count = Counter(self.nums)
10+
# Sort elements by frequency in descending order
11+
sorted_items = sorted(count.items(), key=lambda x: x[1], reverse=True)
12+
return [item[0] for item in sorted_items[:k]]
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import List
2+
from collections import Counter
3+
import heapq
4+
5+
class TopKFrequentHeap:
6+
def __init__(self, nums: List[int]):
7+
self.nums = nums
8+
9+
def top_k_frequent(self, k: int) -> List[int]:
10+
count = Counter(self.nums)
11+
# Use a heap to get the k elements with highest frequency
12+
return [item for item, freq in heapq.nlargest(k, count.items(), key=lambda x: x[1])]

0 commit comments

Comments
 (0)