Kth Largest Element in an Array
Problem Statement
You are given an integer array nums and an integer k. Return the kth largest element in the array.
This means the kth largest in sorted order, counting from the top. It is not the kth distinct value: a value that appears twice takes two positions.
nums, an integer array, and k.
One integer: the kth largest value in nums.
Sorted from biggest: 6, 5, 4, 3, 2, 1. The 2nd value is 5.
Sorted from biggest: 6, 5, 5, 4, 3, 3, 2, 2, 1. The 4th value is 4. The two 5s and the two 3s each take their own position.
- • 1 ≤ k ≤ nums.length ≤ 10^5
- • −10^4 ≤ nums[i] ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Sort from biggest to smallest and read position k − 1
Build a max-heap of all values in O(n); pop the k − 1 biggest; the top is the answer
Keep the k largest seen so far in a min-heap; its top is the kth largest
Sort the array from biggest to smallest. Index 0 is the largest, so the kth largest is at index k − 1. Duplicates keep their own slots, so no special handling is needed.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.