LeetCode 215: Kth Largest Element in an Array Solution
Master LeetCode problem 215 (Kth Largest Element in an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
215. Kth Largest Element in an Array
Problem Explanation
Explanation
To find the kth largest element in an array without sorting, we can use a min-heap data structure. We will maintain a heap of size k, where the top element of the heap will be the kth largest element seen so far. We iterate through the array and add each element to the heap. If the size of the heap exceeds k, we remove the minimum element from the heap. At the end of the iteration, the top element of the heap will be the kth largest element in the array.
- Time complexity: O(n * log k) where n is the number of elements in the array
- Space complexity: O(k)
Solution Code
import java.util.PriorityQueue;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 215 (Kth Largest Element in an Array)?
This page provides optimized solutions for LeetCode problem 215 (Kth Largest Element in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 215 (Kth Largest Element in an Array)?
The time complexity for LeetCode 215 (Kth Largest Element in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 215 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 215 in Java, C++, or Python.