Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 347 · Top K

Top K Frequent Elements

LeetCode 347 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Counter + size-k min-heap on frequency.

మధ్యస్థంArrayHash TableDivide and ConquerSortingHeap (Priority Queue)
LeetCode లో తెరవండి ↗

నేను 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. 1

    Count frequencies.

  2. 2

    Push (count, num); pop when the heap exceeds k.

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