#1985
Find the Kth Largest Integer in the Array
MediumArrayStringDivide and ConquerSortingHeap (Priority Queue)QuickselectHeap (Priority Queue)Sorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n log k) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n log k)Space O(k)
Using a min-heap allows us to efficiently track the k largest elements without sorting the entire array, making this approach faster.
⚙️
Algorithm
4 steps- 1Step 1: Create a min-heap to store the k largest numbers.
- 2Step 2: Iterate through each number in the array and add it to the heap.
- 3Step 3: If the heap exceeds size k, remove the smallest element (the root of the min-heap).
- 4Step 4: After processing all numbers, the root of the heap will be the k-th largest number.
solution.py9 lines
1import heapq
2
3def kthLargestNumber(nums, k):
4 min_heap = []
5 for num in nums:
6 heapq.heappush(min_heap, num)
7 if len(min_heap) > k:
8 heapq.heappop(min_heap)
9 return min_heap[0]ℹ
Complexity note: We maintain a heap of size k, which takes O(log k) time for each of the n elements, resulting in O(n log k) overall.
- 1When comparing strings that represent numbers, the length of the string is the primary factor in determining which is larger.
- 2Using a min-heap allows us to efficiently keep track of the k largest elements without sorting the entire array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.