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