--- title: '215. Kth Largest Element in an Array' description: Given an integer array nums and an integer k, return the k^th largest element in the array icon: dot topics: - { name: "Array", slug: "array" } - { name: "Divide and Conquer", slug: "divide-and-conquer" } - { name: "Sorting", slug: "sorting" } - { name: "Heap (Priority Queue)", slug: "heap-priority-queue" } - { name: "Quickselect", slug: "quickselect" } video: "XEmy13g1Qxc" issue: "https://github.com/prdlk/leetcode/issues/118" companies: - { name: "Meta", period: "Thirty Days", frequency: 70.8 } - { name: "Spotify", period: "Three Months", frequency: 90.3 } - { name: "Bloomberg", period: "Three Months", frequency: 36.8 } - { name: "Google", period: "Three Months", frequency: 32.7 } - { name: "Amazon", period: "Three Months", frequency: 28.9 } - { name: "Walmart Labs", period: "Six Months", frequency: 70.5 } - { name: "IBM", period: "Six Months", frequency: 70.1 } - { name: "LinkedIn", period: "Six Months", frequency: 63.3 } - { name: "Flipkart", period: "Six Months", frequency: 57.1 } - { name: "TikTok", period: "Six Months", frequency: 55.2 } - { name: "Microsoft", period: "Six Months", frequency: 37.9 } sidebar: label: 'Kth Largest Element in an Array' badge: 'Medium' --- ### Example 1: - Input: `nums = [3,2,1,5,6,4], k = 2` - Output: `5` ### Example 2: - Input: `nums = [3,2,3,1,2,4,5,5,6], k = 4` - Output: `4` ### Constraints: - `1 <= k <= nums.length <= 10^5` - `-10^4 <= nums[i] <= 10^4` ## Approach ```mermaid flowchart TD S(["findKthLargest(nums, k)"]) --> F{"more i in range(len(nums))?"} F -- yes --> N["nums[i] = -nums[i] — negate so the min-heap acts as a max-heap"] N --> F F -- no --> H["heapq.heapify(nums)"] H --> W{"more _ in range(k - 1)?"} W -- yes --> P["heapq.heappop(nums) — discard the k-1 largest"] P --> W W -- no --> E(["return -heapq.heappop(nums)"]) ``` ## Solution ```py import heapq class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: for i in range(len(nums)): nums[i] = -nums[i] heapq.heapify(nums) for _ in range(k - 1): heapq.heappop(nums) return -heapq.heappop(nums) ```