FAANG · LeetCode #215
Kth Largest Element in an Array — three-stage drill
1The ProblemMedium
Kth Largest Element in an Array
Given an unsorted array, find the value that would sit at position k if it were sorted descending.
Examples
nums=[3,2,1,5,6,4], k=2→ 5nums=[3,2,3,1,2,4,5,5,6], k=4→ 4
constraint1 ≤ k ≤ nums.length. Solution uses O(n log k) time, O(k) space — better than the naïve sort's O(n log n) when k is small.
2The PatternTIME O(n log k) · SPACE O(k)
Heap / Top-K
A heap keeps one extreme on top: a max-heap the largest, a min-heap the smallest. Inserting bubbles the new item up until the heap order holds — toggle to compare the two.
Problems using this pattern
3The SolutionRESULT → 5
Step through it
given nums of length 6, k = 2 · find the 2nd largest
Step 1 / 21
Arrow keys to navigate · escape to reset