215. Kth Largest Element in an Array LeetCode Solution

In this guide, you will get 215. Kth Largest Element in an Array LeetCode Solution with the best time and space complexity. The solution to Kth Largest Element in an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Kth Largest Element in an Array solution in C++
  4. Kth Largest Element in an Array solution in Java
  5. Kth Largest Element in an Array solution in Python
  6. Additional Resources
215. Kth Largest Element in an Array LeetCode Solution image

Problem Statement of Kth Largest Element in an Array

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?

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 <= 105
-104 <= nums[i] <= 104

Complexity Analysis

  • Time Complexity: O(n\log k)
  • Space Complexity: O(k)

215. Kth Largest Element in an Array LeetCode Solution in C++

class Solution {
 public:
  int findKthLargest(vector<int>& nums, int k) {
    priority_queue<int, vector<int>, greater<>> minHeap;

    for (const int num : nums) {
      minHeap.push(num);
      if (minHeap.size() > k)
        minHeap.pop();
    }

    return minHeap.top();
  }
};
/* code provided by PROGIEZ */

215. Kth Largest Element in an Array LeetCode Solution in Java

class Solution {
  public int findKthLargest(int[] nums, int k) {
    Queue<Integer> minHeap = new PriorityQueue<>();

    for (final int num : nums) {
      minHeap.offer(num);
      while (minHeap.size() > k)
        minHeap.poll();
    }

    return minHeap.peek();
  }
}
// code provided by PROGIEZ

215. Kth Largest Element in an Array LeetCode Solution in Python

class Solution:
  def findKthLargest(self, nums: list[int], k: int) -> int:
    minHeap = []

    for num in nums:
      heapq.heappush(minHeap, num)
      if len(minHeap) > k:
        heapq.heappop(minHeap)

    return minHeap[0]
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.