Faaez Razeen

Kth Largest Element in an Array

  • 3 min read
  • LC-Medium
  • Binary-heap

3 years ago

Solution

TimeSpaceExplanation
O(n^2) worst case, O(n) average caseO()
def findKthLargest(self, nums: List[int], k: int) -> int: n = len(nums) - k def quickSelect(l, r): p = l for i in range(l, r): if nums[i] <= nums[r]: nums[i], nums[p] = nums[p], nums[i] p += 1 nums[p], nums[r] = nums[r], nums[p] if p < n: return quickSelect(p + 1, r) elif p > n: return quickSelect(l, p - 1) return nums[p] return quickSelect(0, len(nums) - 1)

Less Optimal Solution

TimeSpaceExplanation
O(n + k log n)O()O(n) to build the heap, log (n) for each heappop. and we heappop k times
def findKthLargest(self, nums: List[int], k: int) -> int: heapify(nums) while len(nums) > k: heappop(nums) return nums[0]