Skip to content
Problem 215 · LeetCode 215(opens in a new tab)

Kth Largest Element in an Array

MediumArrays

You get a list of whole numbers, nums, and a number k. Return the value that would sit in position k if the list were ordered from largest to smallest.

Repeated values each take their own position, so in [5, 5, 3] both the first and second largest are 5. Try to do better than sorting the whole list.

Example 1

Input:  nums = [7, 2, 9, 4, 1, 8], k = 3
Output: 7
Why:    largest to smallest: 9, 8, 7, ...
2 more examples and the constraints

Example 2

Input:  nums = [5, 5, 3, 5, 1], k = 3
Output: 5
Why:    the three 5s fill the first three places

Example 3

Input:  nums = [6, -3, 0, 2], k = 4
Output: -3
Why:    with k equal to the length, it is the minimum

Constraints

  • 1 ≤ k ≤ length of nums ≤ 100,000
  • −10,000 ≤ each number ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort and indexO(n log n)
  2. Min-heap of size kO(n log k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbers, small kVerdict
Sort and indexO(n log n)
Passes; orders more than needed
Min-heap of size kO(n log k)
Best; one pass, small heap

n = length of nums. When k is close to n, the two cost about the same.

Edge cases to test

  • Repeated values. [5, 5, 3, 5, 1] with k = 3 is 5: duplicates are not merged.
  • k = 1. The answer is the maximum.
  • k = n. The answer is the minimum, e.g. −3 for [6, −3, 0, 2].
  • Negative numbers. [−1, −5, −3, −2] with k = 2 is −2.

Common mistakes

  • Using a max-heap of all n numbers and popping k − 1 times, which costs O(n) memory instead of O(k).
  • Counting only distinct values, so [5, 5, 3] with k = 2 gives 3 instead of 5.
  • Off-by-one on the sorted index: the answer is at n − k, not n − k − 1.

How to talk through it

  1. 1Clarify. Do duplicates count separately? Is k always valid? May I change the input array?
  2. 2Give the sort. Sort and take index n − k; say it is O(n log n) and orders more than we need.
  3. 3Keep only the top k. A min-heap of size k holds the k largest seen so far; its top is the cut-off.
  4. 4Code the heap. Push, and pop when the size passes k. Say why the popped number can never be the answer.
  5. 5Test out loud. Run k = 1, k = n and a list with repeats before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?