AlgoMaster Logo

Kth Largest Element in an Array

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Approach: Sorting

Intuition:

The simplest and most direct way to find the k-th largest element is to sort the array first. Once sorted, the k-th largest can be easily accessed by indexing.

Approach:

  1. Sort the entire array in descending order.
  2. Retrieve the k-th element from the sorted array.

Code:

2. Min-Heap Approach

Intuition:

Instead of sorting the entire array, we can use a min-heap to maintain the k largest elements and efficiently find the k-th largest.

Approach:

  1. Create a min-heap of size k.
  2. Iterate through each element of the array.
    • If the heap size is less than k, add the element to the heap.
    • Else if the current element is larger than the smallest element in the heap, replace the smallest.
  3. The top of the heap will be the k-th largest element.

Code:

3. Quickselect (Optimal)

Intuition:

Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is based on the QuickSort algorithm. Instead of recursing both sides of the pivot, we only recurse into the part that contains the k-th element.

Approach:

  1. Use a partition method to place the pivot at its correct position in a sorted array.
  2. If the pivot is at index n-k, return its value.
  3. Otherwise, recurse on the subarray containing the k-th largest element.

Code: