Here is the interview question prompt, presented for reference.
We're given a list or array of numbers, like the following:
const nums = [5, 16, 7, 9, -1, 4, 3, 11, 2]
Can you write an algorithm to find the k
largest values in a list of n
elements? If k
were 3
, we'd want the three largest numbers returned. The correct logic would return [16, 11, 9]
. Order is not a consideration.
Can you find more than one approach to this problem?
100000
-1000000000
and 1000000000
O(n logk)
where k
is the size of the heapO(k)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for K Largest Elements From List.
Hi!
I think there is a mistake in lecture about type of PQ
and its relation with space complexity
If expected space complexity is O(k)
then we need use min-PQ
so when capacity reached k
we be able to pop out min value so far and add new value that is greater then popped
Here is my solution in Java
import java.util.*;
public class Main {
public static int[] kLargest(int[] nums, int k) {
int n = nums.length;
PriorityQueue pq = new PriorityQueue(k, (a, b) -> a - b);
for (int i = 0; i < n; i++) {
int val = nums[i];
if (pq.size() < k) {
pq.add(val);
} else {
int min = pq.peek();
if (val > min) {
pq.poll();
pq.add(val);
}
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = pq.poll();
}
return result;
}
public static void main(String[] args) {
// print [-1, 2, 9, 11, 17, 29]
System.out.println(
Arrays.toString(Main.kLargest(new int[] {29, 17, 9, -1, -3, 11, 2}, 6))
);
// print [9, 11, 16]
System.out.println(
Arrays.toString(Main.kLargest(new int[] {5, 16, 7, 9, -1, 4, 3, 11, 2}, 3))
);
}
}
```
Hi, there!
On Safari version 14.1 images from lecture are displayed 90 degree rotated clockwise. MacOS Big Sur, Version 11.3.1