Back to All Questions
Kth Largest Element in an Array
Google
Array
Heap
Sorting

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

Note that it is the kth largest element in sorted order, not the kth distinct element.

Example:

Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Solution Walkthrough

Sorting the whole array and reading off the kth-from-the-end element works in O(n log n), but a min-heap of size k does better — O(n log k).

  1. Walk through nums and push each value onto a min-heap.
  2. Whenever the heap grows past size k, pop its minimum — this discards elements that can't possibly be among the k largest.
  3. After processing every element, the heap contains exactly the k largest values, and its root (the minimum of that set) is the answer.

Because the heap never holds more than k elements, each push/pop is O(log k), giving an overall time complexity of O(n log k) and space complexity of O(k).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Related Algorithms