701353. Kth largest element

Medium

Kth largest element

Summary

Given an unsorted array, find the k-th largest element. This problem involves using a priority queue or heap data structure to efficiently extract the k-th largest element.

Detailed Explanation

To solve this problem, we can use a max-heap to store the elements of the array. The idea is to insert all elements into the max-heap and then pop k-1 times to get the k-th largest element.

Here's a step-by-step breakdown of the solution:

  1. Create an empty max-heap.
  2. Iterate through the array, inserting each element into the max-heap.
  3. Pop k-1 times from the max-heap to discard the k-1 smallest elements.
  4. The top element in the max-heap is the k-th largest element.

The time complexity of this solution is O(n log n) due to the insertion and pop operations on the heap, where n is the size of the array. The space complexity is O(n) for storing the elements in the heap.

Here's an ASCII art diagram illustrating the steps:

  +---------------+
  |  Max-Heap     |
  +---------------+
           |
           v
  +---------------+
  |  Element 1    |
  |  Element 2    |
  |  ...          |
  |  Element n    |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.PriorityQueue;

public class KthLargestElement {
    public static int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b.compareTo(a));
        for (int num : nums) {
            maxHeap.offer(num);
        }
        for (int i = 0; i < k - 1; i++) {
            maxHeap.poll();
        }
        return maxHeap.peek();
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.