Kth Largest Element in an Array solution explained

To find the kth largest element in an array, keep a min-heap of the k largest values seen so far: its root is the answer, in O(n log k) time and O(k) space. For average linear time, use quickselect, which partitions around a random pivot and keeps only the side that holds the answer. Duplicates count as separate elements, so in [8, 1, 8, 5, 3] the second largest is 8.

By Published 8 min read

What is being asked

Given an unsorted list of integers and a number k between 1 and the length of the list, return the kth largest value. Equal values each take their own position: the question is about positions in sorted order, not about distinct values. Many versions of the question also ask you to beat a full sort, which is the real point of the exercise.

Arrays and answers prepared for this page
ArraykAnswerSorted from largest
[8, 1, 8, 5, 3]288, 8, 5, 3, 1
[8, 1, 8, 5, 3]438, 8, 5, 3, 1
[-4, -9, -1]3-9-1, -4, -9
[6]166
[2, 2, 2, 2]32Every position holds 2
Arrays and answers prepared for this page. Scroll sideways on a small screen.

Clarify three things before you start: whether duplicates count separately (they normally do), whether you may change the input array, and how large n and k can get. If you may not touch the input, quickselect has to work on a copy, which costs O(n) memory.

What the interviewer learns

There are three good answers with different trade-offs, and the question is mostly about choosing between them and saying why. A candidate who only sorts shows little. One who jumps straight to quickselect without mentioning its worst case shows memorization. The strongest answers start with the heap, then offer quickselect for average linear time and explain what protects it from bad pivots.

Common follow-ups

  • The values arrive as a stream and you must answer after each one. Keep the size-k min-heap alive between calls. Each new value costs O(log k).
  • k is close to n. The kth largest is the (n - k + 1)th smallest, so a max-heap of size n - k + 1 is smaller. Say this out loud; it shows you think about the constants.
  • Values are bounded, say 0 to 10,000. Count occurrences in an array of that size and walk down from the top until k values are covered. That is O(n + range).
  • Linear time even in the worst case. The median-of-medians pivot rule does that. Few people code it in an interview; knowing it exists is usually enough.
  • The data is split across machines. Each machine sends its own top k; merge those candidate lists and select again.

Starting point: sort and index

Sort ascending and return the element at index n - k, or sort descending and return index k - 1. It takes one line in most languages and O(n log n) time. State it, give the complexity, and ask whether the interviewer wants something faster. Usually they do.

A heap that holds only k values

Seed a min-heap with the first k elements. For each later value, if it is larger than the heap's root, replace the root with it. The root is always the smallest of the k largest values seen so far, which is exactly the kth largest. Every comparison against the root is O(1) and every replacement is O(log k), so the total is O(n log k), and memory stays at O(k) no matter how long the input is.

import heapq


def kth_largest_heap(nums, k):
    heap = nums[:k]          # min-heap of the k largest values seen so far
    heapq.heapify(heap)
    for x in nums[k:]:
        if x > heap[0]:
            heapq.heapreplace(heap, x)
    return heap[0]
Min-heap of size k. O(n log k) time, O(k) extra space.

heapreplace pops the root and pushes the new value in one O(log k) step, which is slightly cheaper than a separate pop and push. The strict greater-than test means equal values do not churn the heap, and the answer is still right because duplicates of the root are interchangeable.

Quickselect for average linear time

Quickselect is quicksort that only recurses into one side. Pick a random pivot and split the range into values below it, equal to it and above it. If the target index falls inside the equal block, the pivot is the answer. Otherwise continue in the side that contains the target and discard the other. With a random pivot the range shrinks by a constant fraction per step on average, so the expected total work is a constant multiple of n, which is O(n). The three-way split matters: a plain two-way partition slows to quadratic time on an array full of copies of one value, because every pivot then fails to shrink the range. The same three-region split solves Sort Colors.

import random


def kth_largest(nums, k):
    a = list(nums)
    want = len(a) - k            # the answer's index in ascending order
    lo, hi = 0, len(a) - 1
    while True:
        pivot = a[random.randint(lo, hi)]
        # Three-way split of a[lo..hi]: smaller, equal, larger than pivot
        lt, i, gt = lo, lo, hi
        while i <= gt:
            if a[i] < pivot:
                a[lt], a[i] = a[i], a[lt]
                lt += 1
                i += 1
            elif a[i] > pivot:
                a[gt], a[i] = a[i], a[gt]
                gt -= 1
            else:
                i += 1
        if want < lt:
            hi = lt - 1
        elif want > gt:
            lo = gt + 1
        else:
            return pivot
Quickselect with a random pivot and three-way partition. O(n) average, O(n²) worst case.

The function copies the input first so the caller's list is untouched. If the interviewer allows modifying the input, drop the copy and the extra space falls to O(1). The loop is iterative, so there is no recursion depth to worry about.

#include <algorithm>
#include <functional>
#include <queue>
#include <vector>

int kthLargestHeap(const std::vector<int>& nums, int k) {
    // greater<int> turns priority_queue into a min-heap
    std::priority_queue<int, std::vector<int>, std::greater<int>> best;
    for (int x : nums) {
        best.push(x);
        if (static_cast<int>(best.size()) > k) best.pop();
    }
    return best.top();
}

int kthLargestLibrary(std::vector<int> nums, int k) {
    // nth_element partially orders the copy around position k - 1
    std::nth_element(nums.begin(), nums.begin() + (k - 1), nums.end(),
                     std::greater<int>());
    return nums[k - 1];
}
C++: a size-k min-heap, and the standard library's own selection routine.

std::nth_element is the library version of quickselect and runs in linear time on average. Taking the vector by value makes the copy explicit. In an interview, ask whether library selection is allowed; some interviewers accept it and then ask you to write the partition yourself.

Choosing between them

n elements, looking for the kth largest
MethodTimeExtra spaceChoose it when
Sort, then indexO(n log n)O(1) to O(n), depends on the sortSimplicity matters more than speed
Min-heap of size kO(n log k)O(k)k is small, or values arrive as a stream
Quickselect, random pivotO(n) average, O(n²) worstO(1) in placeOne query on an array you may reorder
Counting over a bounded rangeO(n + range)O(range)Values fit in a small known range
n elements, looking for the kth largest. Scroll sideways on a small screen.

Inputs worth trying

  • k = 1 (the maximum) and k = n (the minimum).
  • All values equal, which breaks a naive two-way partition's speed.
  • Duplicates around the answer, as in [8, 1, 8, 5, 3] with k = 2.
  • Negative numbers only.
  • An already sorted array, the classic bad case for a pivot that is always the first or last element.

Frequent errors

  • Using a max-heap of all n values and popping k times. It works, but it is O(n + k log n) and misses the point of the size-k heap.
  • Off-by-one on the target index: the kth largest sits at index n - k in ascending order, not n - k - 1.
  • Removing duplicates first, which changes the answer.
  • Choosing the first element as the pivot and never mentioning the sorted-input worst case.
  • Claiming quickselect is O(n) without the word average.

Saying it out loud

Fictional example

Presenting the trade-off in under a minute
Candidate
Sorting gives n log n. I can do better because I need one position, not the whole order.
Candidate
Option one is a min-heap that never holds more than k values. Its root is the kth largest so far. That's n log k time and k space, and it also works if the numbers stream in.
Candidate
Option two is quickselect: linear on average with a random pivot, quadratic in the worst case. I'd use a three-way partition so repeated values don't hurt it.
Candidate
For a single query on an array I'm allowed to reorder, I'll write quickselect. If you'd rather avoid the worst case, the heap is safer.

Similar problems

K Closest Points to Origin is the same selection question with distance as the key, and it shows quickselect in JavaScript. Task Scheduler uses a heap to keep the most frequent task on top. Last Stone Weight is a gentler heap warm-up, and Find Median from Data Stream splits the values across two heaps so the middle stays reachable. The problem hub has more.

Where Natively fits in your practice

While you drill selection problems, Natively can take a screenshot of the problem on Mac or Windows and suggest which of the three methods suits the constraints, along with code you can compare to your own. Running a mock round through it gives you a transcript to reread, so you can see whether you remembered to say average for quickselect. Read more about AI help for coding interviews.

Questions people ask

How do you find the kth largest element without sorting?

Keep a min-heap of the k largest values seen so far and return its root, in O(n log k) time. Or use quickselect, which partitions around random pivots and averages O(n).

Is quickselect O(n)?

On average, yes, with a random pivot. In the worst case it is O(n²). The median-of-medians pivot rule makes it linear in the worst case, at the cost of more code and larger constants.

Do duplicates count in Kth Largest Element in an Array?

Yes. The question asks about positions in sorted order, so equal values each take a position. In [8, 1, 8, 5, 3] the first and second largest are both 8.

Should I use a min-heap or a max-heap for the kth largest?

A min-heap of size k. Its root is the smallest of the k largest values, which is the answer. A max-heap of all n values also works but needs O(n) space and k pops.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP