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)

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