15% off all plans & roadmaps Use code

See plans

Kth Largest Element in an Array

Updated

TL;DR: Find the kth largest value in an unsorted array, counting duplicates. Sorting works in O(n log n), a size-k min-heap gives O(n log k), and quickselect gives O(n) on average.

Problem

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

The answer is the kth largest in sorted order. It is not the kth distinct value, so duplicates each take a position.

Example 1

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

Example 2

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

Constraints

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

Constraints that matter

  • n up to 10^5 means O(n^2) is too slow. Scanning for the maximum k times can hit about 10^10 operations when k is near n.
  • n up to 10^5 keeps O(n log n) sorting comfortably fast. A full sort is a valid answer here, and the interview question is whether you can do better.
  • k is at least 1 and at most n, so the answer always exists. You never need to handle k larger than the array.
  • Values are bounded by 10^4 in absolute value, so int arithmetic never overflows. The small range also allows a counting approach, though the general techniques do not rely on it.
  • Duplicates are allowed and each counts, so any method that deduplicates first gives wrong answers.

View on LeetCode

Hints

Hint 1

This is a selection problem.

Hint 2

Sort the array and read the answer off by position.

Solution

Intuition

This is a selection problem. You need one element defined by its rank, not the whole sorted order. Whenever a problem asks for the kth best, the kth smallest, or the top k of something, think Top K Elements with a heap, or partition-based selection.

Picture a row of people sorted by height where you only need whoever stands at one specific spot. The pivot is the person you call out, and the group that cannot hold your spot walks away.

Sorting does more work than needed. It orders all n values, yet you only care where one rank boundary falls. Two ideas avoid the extra work. Keep only the k largest values seen so far, or split the array around a pivot and keep only the side that holds your rank.

The first idea uses a min-heap of size k. The heap holds the k largest values seen so far, and its root is the smallest of them. That root is exactly the kth largest once every value has been seen. A new value that is not bigger than the root cannot help, and a bigger one evicts the root.

The second idea is quickselect. Pick a pivot, split the array into smaller, equal and larger parts, and see which part contains the target position. Throw away the other parts. Each round shrinks the search range, and on average the total work is a geometric series that sums to O(n).

Watch the pattern animation

Worked example

Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Explanation: Sorted in descending order the array is 6, 5, 4, 3, 2, 1. The largest is 6 and the second largest is 5, so the answer is 5.

Approach 1: Sort, then index

Sort the array and read the answer off by position. After an ascending sort, the largest element sits at index n - 1, the second largest at n - 2, and the kth largest at index n - k.

This is the version a beginner writes first. It is correct, short, and handles duplicates for free because every copy keeps its own slot.

Steps

  1. Sort nums in ascending order.
  2. Compute the index n - k where n is the array length.
  3. Return the value at that index.

Dry run

Start with [3, 2, 1, 5, 6, 4] and k = 2.

  • Sorted ascending: [1, 2, 3, 4, 5, 6].
  • n = 6, so the target index is 6 - 2 = 4.
  • The value at index 4 is 5, which matches the expected output.

Complexity

TimeO(n log n)
SpaceO(1) extra for an in-place sort, or O(n) if the sort copies

Here n is the array length. Comparison sorting costs O(n log n) comparisons, and the final lookup is O(1). The sort works in place in most languages, so the extra memory is a small constant for the Go, Java and C# sorts. Some library sorts use O(n) or O(log n) scratch space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        nums.sort()
        # ascending order, so the kth largest is k places from the end
        return nums[len(nums) - k]
Top K Elements (Selection/Frequency) pattern infographic for Kth Largest Element in an Array

Solution pattern

Top K Elements (Selection/Frequency)

Part of Heap (Priority Queue) Patterns

Approach 2: Min-heap of size kTop K Elements (Selection/Frequency)

What's slow: sorting orders all n values, including the n - k small ones you will never return. That is wasted work, and it also forces you to hold the whole array in sorted form.

The insight that fixes it: keep a min-heap that holds only the k largest values seen so far. The root of a min-heap is its smallest element, so the root is the weakest member of the current top k. Push each value, and when the heap grows to k + 1 elements, pop the root. After the last value, the root is the kth largest.

Each push or pop costs O(log k) because the heap never holds more than k + 1 items.

Steps

  1. Create an empty min-heap.
  2. For each value x in nums, push x onto the heap.
  3. If the heap now holds more than k elements, pop the smallest one.
  4. After the loop, the heap holds the k largest values.
  5. Return the root of the heap, which is the smallest of those k values.

Dry run

Run [3, 2, 1, 5, 6, 4] with k = 2. The heap is shown as a sorted set for readability.

ValueAfter pushSize over k?After pop
3{3}no{3}
2{2, 3}no{2, 3}
1{1, 2, 3}yes, pop 1{2, 3}
5{2, 3, 5}yes, pop 2{3, 5}
6{3, 5, 6}yes, pop 3{5, 6}
4{4, 5, 6}yes, pop 4{5, 6}

The heap ends as {5, 6}. Its root is 5, which is the answer.

Complexity

TimeO(n log k)
SpaceO(k)

Here n is the array length and k is the rank. Every element causes one push and at most one pop, and each costs O(log k) because the heap holds at most k + 1 elements. That gives n * O(log k) in total. The heap never exceeds k + 1 entries, so the extra space is O(k).

PythonTested in our runner

import heapq
from typing import List, Optional

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap: List[int] = []
        for x in nums:
            heapq.heappush(heap, x)
            if len(heap) > k:
                # evict the smallest, it cannot be in the top k
                heapq.heappop(heap)
        return heap[0]

Approach 3: QuickselectOptimal

What's slow: the heap still touches every element with a log k cost, and it needs O(k) memory. When k is close to n, log k is about log n, so you gain almost nothing over sorting.

The insight that fixes it: you only need to know which element lands at one sorted position, namely index n - k in ascending order. Pick a random pivot and split the range into three parts: smaller than the pivot, equal to it, and larger. If the target index falls in the equal part, the pivot is the answer. Otherwise the target lies in exactly one other part, so you discard the rest and repeat on it.

The three-way split matters. With many duplicates, a two-way split can leave the range almost unchanged, and the work degrades. Equal values are placed once and never revisited. A random pivot makes the expected total work linear.

Why it is correct. The invariant is that the target index always stays inside the current range from lo to hi. Partitioning puts every value below the pivot before the equal zone and every larger value after it. So the element at the target position must lie in whichever zone contains that index.

Steps

  1. Set lo = 0, hi = n - 1 and target = n - k.
  2. Pick a random index in [lo, hi] and read its value as the pivot.
  3. Partition [lo, hi] in place into three zones: less than, equal to and greater than the pivot. Track the boundaries lt and gt.
  4. If target < lt, set hi = lt - 1.
  5. If target > gt, set lo = gt + 1.
  6. Otherwise target lies in the equal zone, so return the pivot.
  7. Repeat from the pivot step until a value is returned.

Dry run

Run [3, 2, 1, 5, 6, 4] with k = 2, so target = 6 - 2 = 4. Assume the pivots come out as 3 and then 5.

RoundRangePivotArray after partitionlt, gtDecision
10..53[2, 1, 3, 4, 6, 5]2, 2target 4 > gt 2, so lo = 3
23..55[2, 1, 3, 4, 5, 6]4, 4target 4 is in 4..4, return 5

In round 1 the left zone holds {2, 1} and the right zone holds {4, 6, 5}. The pivot 3 sits at index 2, which is below the target index 4, so the left side is discarded. In round 2 the pivot lands exactly at index 4. The answer is 5.

Complexity

TimeO(n) expected, O(n^2) worst case
SpaceO(1)

Here n is the array length. Each round scans the current range once, so its cost is proportional to the range size. A random pivot leaves, in expectation, a range a constant fraction smaller. The sizes sum to a geometric series, n + n/2 + n/4 and so on, which is O(n). A run of bad pivots can remove one element per round, giving O(n^2), but that is vanishingly unlikely. The loop is iterative and the partition is in place, so extra space is O(1).

PythonTested in our runner

import random
from typing import List, Optional

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        lo, hi = 0, len(nums) - 1
        target = len(nums) - k  # index in ascending order
        while True:
            pivot = nums[random.randint(lo, hi)]
            lt, i, gt = lo, lo, hi
            # three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
            while i <= gt:
                if nums[i] < pivot:
                    nums[lt], nums[i] = nums[i], nums[lt]
                    lt += 1
                    i += 1
                elif nums[i] > pivot:
                    nums[i], nums[gt] = nums[gt], nums[i]
                    gt -= 1
                else:
                    i += 1
            if target < lt:
                hi = lt - 1
            elif target > gt:
                lo = gt + 1
            else:
                return pivot

Common mistakes

  • Counting distinct values, for example set(nums) before sorting. The problem counts duplicates, so [3, 3, 3] with k = 2 returns 3. Work on the raw array.
  • Using the wrong index after an ascending sort, such as nums[k - 1] or nums[n - k - 1]. The kth largest in ascending order sits at n - k. Check it on [1, 2] with k = 1, which must give 2.
  • Using a max-heap of size k. A max-heap root is the largest value, not the kth. Use a min-heap, so the root is the smallest of the top k and can be evicted when something bigger arrives.
  • Popping after the loop or checking size > k before the push. The usual form pushes first and then pops when the size is k + 1. Skipping the check, or popping one time too many, returns the (k+1)th or (k-1)th value.
  • Sorting in JavaScript with nums.sort() and no comparator. The default order compares strings, so 10 sorts before 9 and negatives sort wrongly. Pass (a, b) => a - b.
  • Quickselect with a two-way partition and a fixed pivot such as the last element. Sorted input or many equal values then trigger the O(n^2) path. Use a random pivot and a three-way split so equal values are settled in one pass.

Edge cases

  • nums = [5], k = 1: a single element returns 5 with every approach.
  • k = n: the answer is the minimum. For [3, 1, 2] with k = 3 the result is 1, and the heap keeps all elements.
  • k = 1: the answer is the maximum. The heap never holds more than one value.
  • All values equal, for example [7, 7, 7, 7] with k = 2: the answer is 7. Quickselect finishes in one round because every element lands in the equal zone.
  • Negative values and duplicates, such as [-1, -1, -2] with k = 2: sorted ascending is [-2, -1, -1], so the answer is -1.
  • Already sorted or reverse-sorted input of size 10^5: a fixed-pivot quickselect would degrade here, while a random pivot stays linear in expectation.

Follow-ups interviewers ask

Can you solve it without sorting?
Yes. A size-k min-heap runs in O(n log k) time and O(k) space. Quickselect runs in O(n) expected time and O(1) extra space, because it only partitions around a pivot and keeps the side holding index n - k.
How would you handle a stream of numbers where you must report the kth largest after each insert?
Keep the min-heap of size k as persistent state. For each new value, push it and pop if the size passes k. The root is then the answer in O(log k). You cannot use quickselect here because it needs the whole array up front.
What if the data does not fit in memory?
The heap approach still works, because it reads values one at a time and stores only k of them. If k itself is too large, bucket values by range in one pass to find which bucket holds the target rank, then process only that bucket. With the bounded value range in this problem, you can also count occurrences per value and walk the counts from the top.

Kth Largest Element in an Array FAQ

What is the time complexity of Kth Largest Element in an Array?

Sorting costs O(n log n). The min-heap of size k costs O(n log k). Quickselect costs O(n) on average and O(n^2) in the worst case, which a random pivot makes very unlikely.

Why use a min-heap for Kth Largest Element in an Array?

The min-heap root is the smallest of the k largest values seen so far. That is the weakest member of the top k, so it is the one to evict when a larger value arrives. After one pass the root is the kth largest.

Can Kth Largest Element in an Array be solved in O(1) extra space?

Yes, with in-place quickselect, which only swaps elements and keeps a few indices. It does modify the input array. The heap approach needs O(k) space, and a copying sort needs O(n).

Is the kth largest element the same as the kth distinct largest?

No. Duplicates each take a position. In [3, 2, 3, 1, 2, 4, 5, 5, 6] the sorted descending order is 6, 5, 5, 4, 3, 3, 2, 2, 1, so the 4th largest is 4.

Is sorting an acceptable answer for LeetCode 215?

It passes the judge, since n is at most 10^5 and O(n log n) is fast enough. In an interview, state it as the baseline. Then give the heap or quickselect solution to show you can avoid ordering elements you do not need.

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

A min-heap of size k uses O(k) memory and gives the answer at the root. A max-heap over all n values also works by popping k - 1 times, but it costs O(n) space and O(n + k log n) time.

Asked at

See which companies ask this — Pro

Practise it