Top K Frequent Elements
LeetCode 347 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Counter + size-k min-heap on frequency.
আমি Top K Frequent Elements (LeetCode 347) এভাবে সমাধান করেছি — Top K প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Count each value, then keep the k most frequent with a min-heap of (count, value) bounded at size k — the least frequent of the kept ones is always on top and gets evicted first.
Approach
- 1
Count frequencies.
- 2
Push (count, num); pop when the heap exceeds k.
- 3
Return the values left in the heap.
আমি কীভাবে সমাধান করেছি
Counter + min-heapPythonO(n log k) time
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
freq_mpp = Counter(nums)
min_heap = []
for num,count in freq_mpp.items():
heapq.heappush(min_heap,(count,num))
if len(min_heap)>k:
heapq.heappop(min_heap)
return [num for count,num in min_heap]Top K Frequent Elements — সাধারণ প্রশ্ন
Top K Frequent Elements-এর পেছনে intuition কী?
Count each value, then keep the k most frequent with a min-heap of (count, value) bounded at size k — the least frequent of the kept ones is always on top and gets evicted first.
Top K Frequent Elements (LeetCode 347) কীভাবে সমাধান করবেন?
1. Count frequencies. 2. Push (count, num); pop when the heap exceeds k. 3. Return the values left in the heap.
Top K Frequent Elements-এর time আর space complexity কত?
Time: O(n log k)। Space: O(n)। (Accepted approach: Counter + min-heap।)
Top K Frequent Elements-এ সাধারণ ভুলগুলো কী?
Bucket sort by frequency gives O(n).