imashutosh51

Kth Smallest element

Jul 31st, 2022 (edited)
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. //Method 1
  2. """
  3. Time Complexity: O(n log k)
  4. Auxiliary Space: O(k)
  5.  
  6. We maintain a max-heap of size k (implemented using negatives in Python).
  7. The heap always stores the k smallest elements seen so far, and the top
  8. represents the largest among them, i.e., the kth smallest element.
  9. """
  10. import heapq
  11. class Solution:
  12.     def kthSmallest(self, arr, k):
  13.         # max-heap of size k using negatives
  14.         heap = [-x for x in arr[:k]]
  15.         heapq.heapify(heap)
  16.  
  17.         for x in arr[k:]:
  18.             if x < -heap[0]:
  19.                 heapq.heapreplace(heap, -x)  # pop + push in one step
  20.  
  21.         return -heap[0]
  22.  
  23. #Method 2
  24. #Quick select
  25. def partition(arr,l,r):
  26.     pivot=arr[r]
  27.     k=l
  28.     i,j=l,r
  29.     for i in range(l,r):
  30.         if arr[i]<=pivot:
  31.             arr[i],arr[k]=arr[k],arr[i]
  32.             k+=1
  33.     arr[k],arr[r]=arr[r],arr[k]
  34.     return k
  35.  
  36. def fun(arr,l,r,k):
  37.     if l<=r:
  38.         p=partition(arr,l,r)
  39.         if p==k:
  40.             return arr[p]
  41.         elif p<k:
  42.             return fun(arr,p+1,r,k)
  43.         else:
  44.             return fun(arr,l,p-1,k)
  45.            
  46. class Solution:
  47.     def kthSmallest(self, arr, k):
  48.         return fun(arr,0,len(arr)-1,k-1)
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment