150NeetCode 150

67.Kth Largest Element in an Array

MediumHeap / Priority Queue ยท 4/7

Problem

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

This is the k-th largest in sorted order, not the k-th distinct value โ€” duplicates count. Try to solve it without fully sorting the array.

Examples

Input:  nums = [3,2,1,5,6,4], k = 2
Output: 5
Explanation: Sorted descending: [6,5,4,3,2,1] -> 2nd is 5.
Input:  nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
Explanation: Sorted descending: [6,5,5,4,3,3,2,2,1] -> 4th is 4.

Constraints

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

๐Ÿ’ก Key Insight

The k-th largest is the element that would sit at index n - k in ascending order. We do not need the rest of the order: a size-k min-heap keeps just the top k (O(n log k)), and Quickselect partitions around a pivot and discards the side that cannot contain index n - k, giving O(n) on average.

Brute Force (Sorting)

TimeO(n log n)SpaceO(log n)

Intuition

Sort ascending and read index n - k.

Algorithm

  1. Arrays.sort(nums).
  2. Return nums[nums.length - k].

Visualization

nums = [3,2,1,5,6,4], k = 2
sorted = [1,2,3,4,5,6]
index n-k = 4 -> 5

Code

java
import java.util.Arrays;

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k]; // k-th from the end
    }
}

Complexity

  • Time: O(n log n) โ€” sorting.
  • Space: O(log n) โ€” sort recursion stack.

Complexity Comparison

Approach Time Space
Sorting O(n log n) O(log n)
Min-Heap of Size k O(n log k) O(k)
Quickselect (3-way) O(n) average O(1)

Common Pitfalls

  • Off-by-one on the target: the k-th largest is index n - k in ascending order, not k - 1 or n - k - 1.
  • Using a fixed pivot or a 2-way Lomuto partition โ€” LeetCode includes large inputs of identical values that push that version to O(nยฒ) and time out.
  • Advancing i after swapping with gt โ€” the element swapped in from the right has not been classified yet.
  • Deduplicating values: [5,5,4] with k = 2 has answer 5, not 4.