MEDIUM NC#67 Heap / Priority Queue
215. Kth Largest Element in an Array
๐ Problem
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. Can you solve it without sorting?
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
- โขApply Heap reasoning pattern
๐ก Approach
- โ Use min heap of size k to store k largest elements
- โ Heap always contains k largest elements seen so far
- โ Top of heap is kth largest element
- โ Alternative: QuickSelect for average O(n) time
- โ Time: O(n log k), Space: O(k)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse min heap of size k to store k largest elements
- โขHeap always contains k largest elements seen so far
- โขTop of heap is kth largest element
Common Pitfalls
- โขAlternative: QuickSelect for average O(n) time
- โขTime: O(n log k), Space: O(k)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
findKthLargest([3,2,1,5,6,4], 2); Expected:
5 Test Case 2
Not run Input:
findKthLargest([3,2,3,1,2,4,5,5,6], 4); Expected:
4 Test Case 3
Not run Input:
findKthLargest([1], 1); Expected:
1 ๐ Code Editor
๐ค Output