DSA Tracker

Problem

Pattern this teaches:Heap and Top K

Medium

Kth Largest Element in an Array

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
2
Core for
26 roles

The problem

Find the kth largest element in an unsorted integer array without sorting the entire array.

Example 1

Input
nums = [7,3,9,2,6], k = 2
Output
7
Why
Sorted descending: 9,7,6,3,2. The 2nd largest is 7.

Example 2

Input
nums = [5,8,5,2,8,9,3,1], k = 3
Output
8
Why
Descending order 9,8,8,5,5,3,2,1: the 3rd entry is 8 (duplicates count separately).

Example 3

Input
nums = [1], k = 1
Output
1
Why
The lone element is trivially the 1st largest value.

Constraints

  • 1 <= k <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

How to think about it

Updated 2026-09-29

Locating the kth largest element does not require establishing total order across all n items. An order-statistic pivot splits elements into those larger and smaller than itself, placing the pivot in its permanent rank. If that rank matches k, you finish immediately; otherwise, exactly one partition is discarded and the other recursed into.

Approaches, worst first

  1. Complete array sort

    time O(n log n) · space O(1)

    Sort the array ascending and index nums[n - k], or sort descending and take nums[k - 1]. Extremely concise to implement, but orders every single element and pays unnecessary O(n log n) overhead.

  2. Bounded min-heap tracking

    time O(n log k) · space O(k)

    Push elements one by one into a min-heap, popping the root whenever the heap size exceeds k. At the conclusion of the array traversal, the heap holds the k largest values and the top element is the kth largest.

  3. Quickselect partition discardingWrite this one

    time O(n) · space O(1)

    Choose a pivot, partition the array so that elements smaller than the pivot sit to the left and larger to the right, and check the pivot index. Recurse only into the side containing the target rank, halving the search space on average at each step.

Where people lose marks · 3
  • Confusing kth largest with kth distinct element, failing when duplicate values exist in the input.
  • Deterministic pivot selection on already sorted or adversarially constructed arrays causing worst-case quadratic runtime in quickselect.
  • Using a max-heap of size n instead of a min-heap of size k, consuming O(n) space and O(n + k log n) time.

Full solution

Quickselect with a random pivot: one Lomuto partition fixes the pivot at its final rank, and only the side holding index n - k is kept, giving O(n) average time in place. It beats the O(n log k) heap in an interview because it uses no extra space and never orders what it discards.

Python
import random


def find_kth_largest(nums: list[int], k: int) -> int:
    target = len(nums) - k  # index the answer would occupy in ascending order
    lo, hi = 0, len(nums) - 1
    while True:
        # Random pivot keeps sorted or adversarial inputs off the quadratic path.
        pivot_idx = random.randint(lo, hi)
        nums[lo], nums[pivot_idx] = nums[pivot_idx], nums[lo]
        pivot = nums[lo]
        store = lo + 1  # everything before store is < pivot
        for j in range(lo + 1, hi + 1):
            if nums[j] < pivot:
                nums[store], nums[j] = nums[j], nums[store]
                store += 1
        p = store - 1
        nums[lo], nums[p] = nums[p], nums[lo]  # pivot lands at its final rank p
        if p == target:
            return nums[p]
        if p < target:
            lo = p + 1  # answer is in the larger-than-pivot side
        else:
            hi = p - 1
JavaScript
function findKthLargest(nums, k) {
  const target = nums.length - k; // index the answer would occupy in ascending order
  let lo = 0;
  let hi = nums.length - 1;
  while (true) {
    // Random pivot keeps sorted or adversarial inputs off the quadratic path.
    const pivotIdx = lo + Math.floor(Math.random() * (hi - lo + 1));
    [nums[lo], nums[pivotIdx]] = [nums[pivotIdx], nums[lo]];
    const pivot = nums[lo];
    let store = lo + 1; // everything before store is < pivot
    for (let j = lo + 1; j <= hi; j++) {
      if (nums[j] < pivot) {
        [nums[store], nums[j]] = [nums[j], nums[store]];
        store++;
      }
    }
    const p = store - 1;
    [nums[lo], nums[p]] = [nums[p], nums[lo]]; // pivot lands at its final rank p
    if (p === target) return nums[p];
    if (p < target) lo = p + 1; // answer is in the larger-than-pivot side
    else hi = p - 1;
  }
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .