Kth Largest Element in an Array

Medium

Topics
ArrayHeapQuickselect

Given an integer array nums and an integer k (passed as target), return the k-th largest element in the array (in sorted order, not distinct).

Example 1

302112536445
larger valuesthe 2th largest
The 2th largest is 5 — by position in sorted order, so duplicates each take a position.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,2,1,5,6,4], k = 2
Output: 5

Example 2

302132132445565768
larger valuesthe 4th largest
Input:  nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4

Constraints

  • 1 <= k <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

We only need the k-th largest, not a full sort. A min-heap of size k keeps exactly the k largest values seen; its root (the smallest of those) is the k-th largest overall.

Quickselect gives O(n) average time, but the heap is simpler and robust.

Approach

  1. Push each element into a min-heap.
  2. Whenever the heap exceeds size k, pop the smallest.
  3. After all elements, the heap holds the k largest and its root is the answer.

Walkthrough

nums = [3,2,1,5,6,4], k = 2
keep 2 largest: heap ends as [5, 6]; root 5 -> 2nd largest = 5

Complexity

  • Time — O(n log k): n elements, each an O(log k) heap op. Quickselect is O(n) average.
  • Space — O(k): the heap holds at most k elements.

Common Pitfalls

  • sorted(nums)[-k], counting from the back. Indexing from the front gives the k-th smallest, and on the largest valid k it walks off the list with IndexError.
  • Sorting is O(n log n) for an O(n)-average problem. Quickselect, or a size-k min-heap at O(n log k), is the answer an interviewer is usually after -- the sort is here for clarity.

Full Solution — all languages

class Solution:
    def findKthLargest(self, nums, target):
        return sorted(nums)[-target]
SensAI
Beta
Tap the mic to stop voice mode