Kth Largest Element

35 min · findKthLargest()

A tournament has 100,000 scores, but the podium question is narrow: which score sits in position k when the leaderboard runs from highest to lowest?

Given an integer array nums and an integer k, return the k-th largest value. k uses 1-based ranking, so k = 1 asks for the maximum and k = nums.length asks for the minimum.

A few ground rules:

  • Duplicate values occupy separate positions in the ranking. In [9, 9, 4], both the first- and second-largest values are 9.
  • You return the value, not its original index.
  • You don't need to preserve any particular order among equal values.

Constraints

  • 1 <= k <= nums.length <= 100_000
  • -10_000 <= nums[i] <= 10_000

Hints

Set a baseline

Sort a copy from largest to smallest and read position k - 1. It works. Now ask how much of that sorted order you actually use.

Keep only the contenders

A min-heap is a structure that exposes its smallest stored value first. If it holds the k largest values seen so far, its smallest value is exactly the current k-th largest.

Make every new value earn its place

Grow the heap to size k. After that, replace its root only when a new value is larger. Values at or below the root can't enter the final top k.

Follow-up

Can you find the answer in average O(n) time by partitioning the array instead of maintaining a heap?

Visible cases

Examples

Example 1

ready
Input
nums = [
  3,
  2,
  1,
  5,
  6,
  4
]
k = 2
Expected
5
Why
descending order starts 6, 5, so rank 2 is 5

Example 2

ready
Input
nums = [
  3,
  2,
  3,
  1,
  2,
  4,
  5,
  5,
  6
]
k = 4
Expected
4
Why
the ranking starts 6, 5, 5, 4; duplicates consume positions

Example 3

ready
Input
nums = [
  -5,
  -2,
  -9,
  -2
]
k = 3
Expected
-5
Why
among negative values, -2, -2, -5 are the top three

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite