const solve = (nums) => { let left = 0, right = nums.length - 1; while (left < right) { const sum = nums[left] + nums[right]; if (sum === target) return [left, right]; }}
Problem Walkthrough

Kth Largest Element — Complete Problem Walkthrough

LeetCode #215 is the problem that teaches both heap and quickselect. Knowing both approaches and their trade-offs is what interviewers actually want to see.

9 min read|

Kth Largest (#215): heap vs quickselect — know both

The problem that tests your knowledge of heaps, partitioning, and trade-off analysis

Kth Largest Element LeetCode — Why Interviewers Love This Problem

Kth Largest Element in an Array — LeetCode #215 — is one of the most frequently asked medium-difficulty problems in coding interviews. It appears regularly at Amazon, Google, Meta, and Microsoft, and for good reason. This single problem tests whether you understand heaps, partitioning algorithms, and how to reason about time complexity trade-offs under pressure.

What makes this problem special is that it has multiple valid solutions at different complexity levels. Interviewers are not just checking whether you can solve it — they want to see if you can present multiple approaches and articulate why you would choose one over the other. A candidate who only knows the sort-based solution looks very different from one who can discuss heap-based and quickselect-based approaches fluently.

In this walkthrough, you will learn three approaches to solving kth largest element leetcode #215: the naive sort, the min-heap technique, and the optimal quickselect algorithm. More importantly, you will understand when to use each one and how to discuss trade-offs in a way that impresses interviewers.

Understanding the Problem

The problem statement is deceptively simple: given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in sorted order, not the kth distinct element. For example, given nums = [3, 2, 1, 5, 6, 4] and k = 2, the answer is 5 because the sorted array is [6, 5, 4, 3, 2, 1] and the second element is 5.

The critical detail many candidates miss on first read is "not the kth distinct element." If the array is [3, 2, 3, 1, 2, 4, 5, 5, 6] and k = 4, the answer is 4 — not 3. You are counting duplicates. Sorted descending, the array is [6, 5, 5, 4, 3, 3, 2, 2, 1], and position 4 is the value 4. Clarifying this with your interviewer shows attention to detail.

The constraints are generous — array length up to 10^5 and values ranging from -10^4 to 10^4. This means even an O(n log n) sort will pass, but interviewers expect you to do better. The real question is how close to O(n) you can get.

ℹ️

Interview Frequency

Kth Largest Element (#215) is in the top 5 most-asked Medium problems — it appears at Amazon, Google, Meta, and Microsoft as a go-to assessment for heap and partitioning knowledge.

Approach 1: Sort — The Simple Baseline

The most straightforward approach is to sort the array in descending order and return the element at index k - 1. In Python, that is literally one line: return sorted(nums, reverse=True)[k-1]. In JavaScript or Java, sort the array and index from the end. This is the solution you should mention first to show you understand the problem before optimizing.

The time complexity is O(n log n) for the sort, and space complexity is O(n) or O(log n) depending on the sorting algorithm used. While this passes on LeetCode, it does more work than necessary. You are sorting the entire array when you only need one specific element. That observation is the key insight that leads to better solutions.

In an interview, state this approach briefly, confirm the O(n log n) complexity, and then say: "We can do better. We only need the kth largest, not a fully sorted array." This transition shows the interviewer that you think critically about efficiency rather than stopping at the first working solution.

  • Time: O(n log n) — full sort of the array
  • Space: O(n) or O(log n) depending on sort implementation
  • Advantage: Simple, easy to code, no bugs
  • Disadvantage: Sorts the entire array when we only need one element

Approach 2: Min-Heap of Size K

The heap approach is the sweet spot between simplicity and efficiency, and it is the solution most interviewers expect you to present confidently. The idea is to maintain a min-heap of size k. As you iterate through the array, push each element onto the heap. Whenever the heap size exceeds k, pop the smallest element. After processing all elements, the top of the heap is the kth largest.

Why does this work? The min-heap of size k always contains the k largest elements seen so far. The smallest element in that heap — the root — is by definition the kth largest. Every time you encounter a new element larger than the current kth largest, it pushes out the smallest of the top-k group, maintaining the invariant.

In Python, use heapq which implements a min-heap natively. Push each element with heapq.heappush, and when the heap exceeds size k, call heapq.heappop. In Java, use PriorityQueue with default ordering. In JavaScript, you will need a custom min-heap implementation or a library, which is worth mentioning to your interviewer as a language-specific consideration.

The time complexity is O(n log k) because each of the n elements requires at most a log k heap operation. The space complexity is O(k) for the heap. When k is much smaller than n — which it often is — this is a meaningful improvement over sorting. For the kth largest heap approach, this is the go-to solution that balances correctness and performance.

  • Time: O(n log k) — each heap operation is O(log k), performed n times
  • Space: O(k) — the heap never exceeds k elements
  • Advantage: Consistent performance, easy to implement correctly
  • Disadvantage: Still not linear time — can we do better?
💡

Interview Strategy

In interviews, present the heap solution first (O(n log k), easy to code correctly), then mention quickselect as the O(n) average optimization — this shows breadth and the ability to discuss trade-offs.

Approach 3: Quickselect — The Optimal Solution

Quickselect is the algorithm that achieves average O(n) time for the kth largest element. It is based on the same partitioning logic as quicksort, but with a crucial optimization: after partitioning, you only recurse into the half of the array that contains the element you are looking for. This cuts the expected work in half at each step, giving you O(n) average time instead of O(n log n).

Here is how quickselect works. Choose a pivot element. Partition the array so that all elements greater than or equal to the pivot are on the left, and all elements less than the pivot are on the right. After partitioning, the pivot is in its final sorted position. If the pivot is at index k - 1, you have found your answer. If the pivot index is less than k - 1, recurse on the right half. If greater, recurse on the left half.

The key insight is that unlike quicksort, which recurses on both halves, quickselect only recurses on one half. The expected number of comparisons follows the recurrence T(n) = T(n/2) + O(n), which resolves to O(n). This makes the quickselect algorithm the theoretically optimal approach for finding the kth largest element.

The implementation requires care around the partition function. Use the Lomuto or Hoare partition scheme, and always randomize the pivot selection. A deterministic pivot choice — like always picking the first or last element — degrades to O(n^2) on sorted or nearly-sorted input, which is a common edge case in interview test suites.

  1. 1Choose a random pivot element from the current subarray
  2. 2Partition: move elements >= pivot to the left, elements < pivot to the right
  3. 3If pivot lands at index k-1, return the pivot value
  4. 4If pivot index < k-1, recurse on the right subarray
  5. 5If pivot index > k-1, recurse on the left subarray

Kth Largest Quickselect vs Heap — Trade-Offs

This is the section that separates good candidates from great ones. Interviewers who ask leetcode 215 solution often follow up with "which approach would you use in production?" The answer depends on context, and showing you understand the nuance is what earns top marks.

The min-heap approach gives you guaranteed O(n log k) time with O(k) space. It never degrades to quadratic time regardless of input. It also works naturally with streaming data — if elements arrive one at a time, the heap processes each in O(log k) without needing the full array in memory. For production systems where worst-case guarantees matter, the heap wins.

Quickselect gives you O(n) average time with O(1) extra space (in-place partitioning). However, its worst case is O(n^2) when the pivot selection is unlucky. Randomized pivot selection makes the worst case astronomically unlikely — the probability drops exponentially — but "unlikely" is different from "impossible." For one-shot computations on in-memory arrays where average performance matters most, quickselect wins.

A strong interview answer sounds like this: "I would implement the heap solution for correctness and reliability. If profiling showed this was a hot path and k is small relative to n, I would consider quickselect for the average O(n) performance, with randomized pivots to mitigate the worst case." This demonstrates you think about trade-offs like an engineer, not just an algorithm student.

  • Heap: O(n log k) guaranteed, O(k) space, works with streaming data
  • Quickselect: O(n) average, O(n^2) worst case, O(1) extra space, in-place
  • Heap is safer for production — no worst-case surprises
  • Quickselect is faster on average — ideal when you control the input
  • Mentioning both approaches and their trade-offs is what interviewers want to hear
⚠️

Worst-Case Pitfall

Quickselect has O(n^2) worst case on already-sorted input — always randomize the pivot. Some interviewers will specifically ask about the worst case to test your understanding.

What This Problem Teaches — The Top-K Pattern

Kth Largest Element is not just one problem — it is the gateway to an entire family of top k elements leetcode problems. Once you master the heap and quickselect approaches here, you can apply the exact same patterns to Top K Frequent Elements (#347), K Closest Points to Origin (#973), Find K Pairs with Smallest Sums (#373), and many more.

The top-K pattern always follows the same structure: you need to find k elements that satisfy some ranking criterion from a larger set. A min-heap of size k is almost always the cleanest solution. Push elements in, pop when the heap exceeds size k, and the heap maintains your answer set. The only variation is what you use as the comparison key — raw values for kth largest, frequencies for top-K frequent, distances for K closest points.

The quickselect pattern generalizes too. Any problem that asks for the kth-order statistic — kth smallest, kth largest, median — can use partitioning. The median of an array is just the (n/2)th smallest element, which quickselect solves in O(n) average time. This is the foundation of the median-of-medians algorithm that achieves worst-case O(n).

Practice these related problems on YeetCode to build pattern fluency. When you can recognize "this is a top-K problem" within seconds of reading the problem statement, you have internalized the pattern at the level interviewers expect. Flashcard-based spaced repetition is particularly effective here because the recognition step — not the implementation — is what most candidates struggle with under pressure.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now