215. Kth Largest Element in an Array - Detailed Explanation

Problem statement

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 the sorted order, not the kth distinct element.

For example, if the array is sorted in descending order, the kth largest element is the element at index k-1.

This question is an instance of the Top K Elements pattern. In that pattern you never sort the whole input. You keep a heap of exactly k items, which is a structure that always hands you its smallest or largest member in constant time, and the heap holds the running answer as the scan proceeds. Several interview favorites reduce to it, and the summary of the most common LeetCode patterns shows where it sits among the rest.

Examples

Example 1

  • Input: nums = [3, 2, 1, 5, 6, 4], k = 2.
  • Output: 5.
  • Explanation: When sorted in descending order, the array becomes [6, 5, 4, 3, 2, 1]. The 2nd largest element is 5.

Example 2

  • Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4.
  • Output: 4.
  • Explanation: When sorted in descending order, the array becomes [6, 5, 5, 4, 3, 3, 2, 2, 1]. The 4th largest element is 4.

Approaches

Three approaches solve this problem, and they trade work against simplicity in different ways.

1. Sorting

  • Idea: Sort the array in descending order and return the element at index k-1.
  • Pros: Simple to implement, and hard to get wrong under pressure.
  • Cons: Sorting the entire array takes O(n log n) time. That is more work than the question needs, since only one element is required.

2. Min heap (priority queue)

  • Idea: Maintain a min heap of size k. Iterate through the array and add each element to the heap. If the heap size exceeds k, remove the smallest element. After processing all elements, the top of the heap is the kth largest element.
  • Pros: Efficient when k is small relative to n. The time complexity is O(n log k).
  • Cons: Requires additional space for the heap.

3. Quickselect

  • Idea: Use the quickselect algorithm, which borrows the partition step from quicksort. Instead of sorting the whole array, partition it around a pivot, so that elements less than the pivot come before it and greater elements come after it. Then recurse only into the part that contains the kth largest element.
  • Pros: Average time complexity of O(n), with no extra data structure.
  • Cons: More complex to implement, and the worst case is O(n²) when the pivots split the array badly.

Detailed explanation of the min heap approach

  1. Initialize a min heap: Create an empty min heap that will store up to k elements.

  2. Process each element in the array:

    • For each element in nums, add it to the min heap.
    • If the heap size exceeds k, remove the smallest element, which is the root of the min heap.
    • The heap therefore always contains the k largest elements seen so far.
  3. Final result: Once all elements are processed, the smallest element in the min heap is the kth largest element overall.

The whole method rests on one invariant: the root of a size-k min heap is the smallest of the k best values, which is exactly the kth largest. Design Gurus walks through this problem in the Kth Largest Element in an Array lesson of Grokking the Coding Mock Interview, in the format of a timed round.

Python code

Python3
Python3

. . . .

Java code

Java
Java

. . . .

Complexity analysis

  • Time complexity:

    • Sorting approach: O(n log n).
    • Min heap approach: O(n log k), since each insertion and each deletion in a heap of size k takes O(log k).
    • Quickselect approach: average O(n), worst case O(n²).
  • Space complexity:

    • Sorting approach: O(1) if the sort is in-place, otherwise O(n).
    • Min heap approach: O(k).
    • Quickselect approach: O(1) extra space when done in-place.

State the heap bound as O(n log k) rather than O(n log n) when an interviewer asks. The distinction matters whenever k is far smaller than n, which is the case the pattern is built for.

Common mistakes and edge cases

  • Incorrect heap size: Letting the heap grow past k, or trimming it to k-1, returns a neighbor of the answer rather than the answer.

  • Handling negative numbers: Check that negative values flow through the heap or the partition step without special cases. Nothing in either method assumes positive input.

  • Edge case, a single element: When the array contains only one element, that element is the kth largest regardless of k, which will be 1.

  • Reversed comparator: A max heap of size k solves the kth smallest problem, not this one. Mixing up the two is a common slip, and the fix is to name the invariant out loud before writing code.

  • Kth Smallest Element in a Sorted Matrix: Finds an order statistic in a matrix with sorted rows and columns, using a heap seeded with the first column.

  • Top K Frequent Elements: Counts occurrences first, then keeps the k most frequent with the same size-k heap. It appears on the Blind 75 list, and it is the closest match to this question.

  • Median of Two Sorted Arrays: Another selection problem, solved by binary search over the split point rather than by a heap.

For the broader map, the article on the recurring LeetCode patterns places Top K Elements beside the other techniques worth drilling, and Grokking the Coding Interview covers each of them with practice problems.

TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
What is a backend developer?
Does IBM provide laptops?
What is the method of interview?
What is the best color to wear for a Zoom presentation?
What is online coding challenge?
Which website is best for coding?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.