9.9 Top K Elements
9.9.1 Problem Metadata
- Platform: Interview Prep
- Problem ID: Top K Elements
- Difficulty: Medium
- URL: N/A
- Tags:
- Techniques: Sorting, Heap, Bubble Sort, Array
9.9.2 Description
Given an unsorted array nums and an integer k, return the k largest elements. The order of the result can be either sorted descending or unspecified depending on the approach.
9.9.5 Solution 1 - Sort Then Slice
9.9.5.1 Walkthrough
Sort the entire array in ascending order and copy the last k values, reversing if descending order is required. This is simple but costs O(n log n).
9.9.6 Solution 2 - Partial Bubble (k Passes)
9.9.6.1 Walkthrough
Bubble sort guarantees that after one full pass the largest element bubbles to the end. Running only k passes yields the k largest elements at the array tail without fully sorting the remainder.
9.9.6.3 Implementation Steps
- Repeat
ktimes:- Sweep the array bubbling the largest remaining element to the end.
- Read off the last
kpositions as the answer.
9.9.6.4 Code - Java
public int[] topKByPartialBubble(int[] nums, int k) {
for (int pass = 0; pass < k; pass++) {
for (int j = 0; j < nums.length - pass - 1; j++) {
if (nums[j] > nums[j + 1]) {
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = nums[nums.length - 1 - i];
}
return result;
}9.9.7 Solution 3 - Min Heap of Size k
9.9.7.1 Walkthrough
Maintain a min heap that stores the current k largest numbers. Push each number and pop whenever the heap size exceeds k. After processing all numbers the heap contains exactly the answer set, and polling yields increasing order.
9.9.7.3 Implementation Steps
- Initialize an empty min heap.
- For each
numinnums, push it; if heap size exceedsk, pop the smallest. - Extract remaining heap elements into the answer array (reverse if descending needed).