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