imashutosh51

K’th largest element in a stream

Aug 5th, 2022 (edited)
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. '''
  2. Logic:
  3. take a min heap and push the element if size of min heap is less than k.
  4. if min heap size is k so,kth maxium element will be at top of min heap
  5. so if current element is smaller than top of min heap then it will not
  6. contribute in kth maximum element else pop top element and push current
  7. element at top.
  8. every time kth maxiumum element will be at top if min heap size is k
  9. '''
  10. from heapq import heappush, heappop
  11. class Solution:
  12.     def kthLargest(self, arr, k):
  13.         heap = []
  14.         res = []
  15.        
  16.         for num in arr:
  17.             if len(heap) < k:
  18.                 heappush(heap, num)
  19.             elif num > heap[0]:
  20.                 heappop(heap)
  21.                 heappush(heap, num)
  22.            
  23.             if len(heap) < k:
  24.                 res.append(-1)
  25.             else:
  26.                 res.append(heap[0])
  27.        
  28.         return res
  29.  
Advertisement
Add Comment
Please, Sign In to add comment