CodingNodes / Heap / Priority Queue / Kth Largest Element In An Array System design Space play · ←→ step · R restart

Problem

Given an integer array nums and an integer k, return the kth largest element. This is the element at position k when the array is sorted from largest to smallest, so duplicates count separately: in [5, 5, 2] the 2nd largest is 5.

Try to do better than sorting the whole array.

Constraints

  • 1 ≤ k ≤ nums.length ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n log k) SpaceO(k)

Time: Each of the n numbers does one push and at most one pop on a heap of at most k + 1 items, and sifting walks at most log k levels.

Space: The heap never keeps more than k numbers.

Keep only the k largest numbers seen so far in a min-heap. Its root, the smallest of them, is the kth largest. After each push, if the heap holds more than k items, pop the root: the smallest of k + 1 numbers cannot be in the top k. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.