# 215. Kth Largest Element in an Array Leetcode Solution

## Kth Largest Element in an Array Leetcode Problem :

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

## Kth Largest Element in an Array Leetcode Solution :

### Constraints :

• 1 <= k <= nums.length <= 10^5
• -10^4 <= nums[i] <= 10^4

### Example 1:

• Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
• Output: 4

Intuition :

The intuition for arriving at this solution is grounded in the properties of a max heap (priority queue) and the goal of efficiently finding the kth largest element in an array.

Approach :

1. Priority Queue (Max Heap): The priority_queue in C++ is implemented as a max heap, which means that the element with the highest value will always be at the top of the heap. This is useful for finding the kth largest element because we want to keep track of the largest elements while discarding the smaller ones.

2. Initialization: The priority queue is initialized with the elements from the nums vector. This will automatically build the max heap, with the largest element at the top.

3. Adjusting k: Since we’re interested in finding the kth largest element, we need to adjust the value of k by subtracting 1. This is because the top element of the max heap is the 1st largest element, the next top element will be the 2nd largest, and so on.

4. Loop to Pop Elements: The loop iterates k times, and in each iteration, it removes the top element (the largest element) from the priority queue using pq.pop(). This effectively removes the k-1 largest elements from the heap.

5. Returning Result: After the loop, the priority queue will only contain the kth largest element (since k-1 larger elements have been removed), and this element is returned as the result.

In summary, this code leverages the properties of a max heap (implemented as a priority queue) to find the kth largest element efficiently. By removing the top element (the largest) k-1 times, the code isolates and returns the kth largest element remaining in the heap. This approach ensures that we don’t need to sort the entire array, making the solution more efficient, especially for large arrays.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others