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).