Kth Largest Element in an Array (LeetCode 215) Solution

Kth Largest Element in an Array 2026 - CodingHumans

Kth Largest Element in an Array (LeetCode 215) is one of those problems that shows up again and again in coding rounds, because it has an easy answer, a good answer and a great answer. Interviewers want to see you move from one to the next and explain the trade-off.

In this post we go through all three: sorting, a min-heap and quickselect, with working code in Java, C++, Python and JavaScript. Every snippet here was run against the LeetCode examples and thousands of random tests before it went on this page.

The problem

You get an integer array nums and an integer k. Return the kth largest element in the array, meaning the kth largest in sorted order, not the kth distinct value.

InputOutputWhy
nums = [3,2,1,5,6,4], k = 25Sorted from largest: 6, 5, 4, 3, 2, 1
nums = [3,2,3,1,2,4,5,5,6], k = 44Sorted from largest: 6, 5, 5, 4, … (both 5s count)

Constraints on LeetCode: 1 ≤ k ≤ nums.length ≤ 105 and values between -104 and 104. The problem also asks whether you can do it without sorting, which is a hint about where the interview is going.

Approach 1: Sort the array

The obvious answer: sort in ascending order, then the kth largest sits at index n - k. Always say this first in an interview. It is correct, it takes ten seconds, and it gives you a baseline to improve on.

Java

import java.util.Arrays;

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);              // ascending
        return nums[nums.length - k];   // k-th from the end
    }
}

Python

def find_kth_largest(nums, k):
    return sorted(nums)[len(nums) - k]

Time: O(n log n)   Space: O(1) to O(n), depending on the sort. It passes LeetCode, but it does more work than needed: we sort all n numbers just to find one of them.

Approach 2: Min-heap of size k

Here is the idea that most interviewers are waiting for. Walk through the array and keep only the k largest numbers seen so far in a min-heap. Whenever the heap grows past k, throw out its smallest number. At the end, the heap holds exactly the k largest values, and its top (the smallest of them) is the kth largest.

Dry run on [3,2,1,5,6,4] with k = 2:

ReadHeap after pushSize > k?Heap after
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 top of the heap is 5, which is the answer.

Java

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
    for (int x : nums) {
        heap.offer(x);
        if (heap.size() > k) heap.poll(); // drop the smallest
    }
    return heap.peek(); // smallest of the k largest
}

C++

int findKthLargest(vector<int>& nums, int k) {
    priority_queue<int, vector<int>, greater<int>> heap; // min-heap
    for (int x : nums) {
        heap.push(x);
        if ((int)heap.size() > k) heap.pop(); // drop the smallest
    }
    return heap.top(); // smallest of the k largest
}

Python

import heapq

def find_kth_largest(nums, k):
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)   # drop the smallest
    return heap[0]

# one-liner with the same idea:
# return heapq.nlargest(k, nums)[-1]

JavaScript has no built-in priority queue, so in an interview you either write a small heap (below) or say you would use a library. Writing it yourself is a nice bonus point if you have time.

JavaScript

// Minimal min-heap, because JavaScript has no built-in priority queue
class MinHeap {
  constructor() { this.a = []; }
  size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) {
    const a = this.a; a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (a[p] <= a[i]) break;
      [a[p], a[i]] = [a[i], a[p]]; i = p;
    }
  }
  pop() {
    const a = this.a, top = a[0], last = a.pop();
    if (a.length) {
      a[0] = last; let i = 0;
      while (true) {
        const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && a[l] < a[m]) m = l;
        if (r < a.length && a[r] < a[m]) m = r;
        if (m === i) break;
        [a[m], a[i]] = [a[i], a[m]]; i = m;
      }
    }
    return top;
  }
}

function findKthLargest(nums, k) {
  const heap = new MinHeap();
  for (const x of nums) {
    heap.push(x);
    if (heap.size() > k) heap.pop(); // drop the smallest
  }
  return heap.peek();
}

Time: O(n log k), since each push or pop costs log k. Space: O(k). When k is small compared to n, this is much faster than sorting, and it also works when the numbers arrive one by one as a stream.

Approach 3: Quickselect (average O(n))

Quickselect borrows the partition step from quicksort. Pick a pivot and split the array into "smaller than pivot", "equal to pivot" and "bigger than pivot". Now you know exactly where the pivot block would sit in sorted order. If the index you want (n - k) is inside that block, you are done. If not, you only continue on the one side that contains it and ignore the other side completely. That skipping is what brings the average time down to O(n).

Two details make or break this on LeetCode:

  • Pick a random pivot. Always taking the first or last element gives O(n²) on sorted input, and LeetCode has such tests.
  • Use a three-way partition. With a plain two-way partition, an array where every value is the same also degrades to O(n²). Grouping equal values together fixes it.

Java

public int findKthLargest(int[] nums, int k) {
    Random rand = new Random();
    int target = nums.length - k;   // index in ascending order
    int lo = 0, hi = nums.length - 1;
    while (true) {
        int pivot = nums[lo + rand.nextInt(hi - lo + 1)];
        // three-way partition: [lo..lt-1] < pivot, [lt..gt] == pivot, [gt+1..hi] > pivot
        int lt = lo, i = lo, gt = hi;
        while (i <= gt) {
            if (nums[i] < pivot) swap(nums, lt++, i++);
            else if (nums[i] > pivot) swap(nums, i, gt--);
            else i++;
        }
        if (target < lt) hi = lt - 1;        // answer is in the left part
        else if (target > gt) lo = gt + 1;   // answer is in the right part
        else return pivot;                   // target landed in the pivot block
    }
}

private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

C++

int findKthLargest(vector<int>& nums, int k) {
    int target = nums.size() - k, lo = 0, hi = nums.size() - 1;
    mt19937 rng(random_device{}());
    while (true) {
        int pivot = nums[lo + rng() % (hi - lo + 1)];
        int lt = lo, i = lo, gt = hi;
        while (i <= gt) {
            if (nums[i] < pivot) swap(nums[lt++], nums[i++]);
            else if (nums[i] > pivot) swap(nums[i], nums[gt--]);
            else i++;
        }
        if (target < lt) hi = lt - 1;
        else if (target > gt) lo = gt + 1;
        else return pivot;
    }
}

// Or let the STL do quickselect for you:
// nth_element(nums.begin(), nums.begin() + (nums.size() - k), nums.end());
// return nums[nums.size() - k];

Time: O(n) on average, O(n²) in the worst case (very unlikely with a random pivot). Space: O(1) extra, because it works in place. Note that it rearranges the input array, so mention that if the caller needs the original order.

Which one should you use?

ApproachTimeExtra spaceUse it when
SortO(n log n)O(1)–O(n)You need a quick, safe answer or the array is tiny
Min-heap of size kO(n log k)O(k)k is small, or data comes as a stream (best default in interviews)
QuickselectO(n) averageO(1)You want the fastest average time and can modify the array

A good interview flow: say the sorting idea in one line, code the heap, then explain quickselect and its average versus worst case. If the interviewer pushes, code quickselect too.

Common mistakes

  • Off-by-one on the index. After an ascending sort, the kth largest is at n - k, not k or n - k - 1. Check it with k = 1: you should get the last element.
  • Removing duplicates. Converting the array to a set changes the answer. The problem counts repeated values.
  • JavaScript's default sort. [10, 9, 2, 1].sort() gives [1, 10, 2, 9] because it compares as strings. Always pass (a, b) => a - b.
  • Using a max-heap with all n elements and calling it optimal. It works, but it needs O(n) memory, which is exactly what the size-k min-heap avoids.
  • Quickselect with a fixed pivot or a two-way partition, which times out on sorted arrays or arrays full of equal values.

Interview follow-ups to prepare

  • Kth smallest element: same ideas with the roles flipped (max-heap of size k, or target index k - 1 in quickselect).
  • Kth Largest Element in a Stream (LeetCode 703): keep the size-k min-heap as a class field and answer after every new number. Quickselect does not work here.
  • Top K Frequent Elements (LeetCode 347): count with a hash map, then use the same size-k heap on the counts.
  • K Closest Points to Origin (LeetCode 973): a heap of size k on the distance.

If heaps still feel shaky, revise them with our Heaps and Hashing MCQs, and follow the DSA roadmap for the order in which to learn these patterns.

FAQ

What is the best approach for Kth Largest Element in an Array?

In an interview, start with the min-heap of size k: it is O(n log k), simple to code and hard to get wrong. Then mention quickselect, which is O(n) on average, and explain why a random pivot matters.

Does the kth largest element mean the kth distinct value?

No. Duplicates count. In [3, 2, 3, 1, 2, 4, 5, 5, 6] with k = 4 the answer is 4, because the sorted order is 6, 5, 5, 4, and the two 5s take two places.

Why do we use a min-heap and not a max-heap for the kth largest?

The min-heap keeps only the k largest numbers seen so far, and its top is the smallest of them, which is exactly the kth largest. A max-heap would have to hold all n numbers and pop k times, which uses O(n) memory.

Can we solve Kth Largest Element without sorting?

Yes. Both the heap and quickselect avoid a full sort. Quickselect only partitions the side of the array that contains the answer, which is why its average time is O(n) instead of O(n log n).

Preparing for coding rounds with friends? Join the CodingHumans WhatsApp community to get new solutions and practice sets as soon as they go live.

Comments

Answered 0/0Correct 0