Problem
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.

given an array and a k, what's the kᵗʰ largest value?nums302112536445k = 2sorted ↓6543212nd largestreturn5
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.

a max-heap keeps the LARGEST on top — a new item bubbles up while it's bigger than its parent50▲ max0301402103204355456↑ inew item 45 lands at the next leaf
Problems using this pattern
3The SolutionRESULT → 5

Step through it

nums321564
given nums of length 6, k = 2 · find the 2nd largest
Step 1 / 21
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent