Good morning! Here's our prompt for today.
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?
Constraints
- Length of the array <=
100000
- The array will contain values between
-1000000000
and1000000000
- The final answer will always fit in the integer range
- Expected time complexity :
O(n logk)
wherek
is the size of the heap - Expected space complexity :
O(k)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
34
var assert = require('assert');
​
function kLargest(nums, k) {
// fill in
return nums;
}
​
try {
assertSameMembers(kLargest([5, 16, 7, 9, -1, 4, 3, 11, 2], 3), [9, 11, 16]);
​
console.log(
'PASSED: `kLargest([5, 16, 7, 9, -1, 4, 3, 11, 2], 3)` returns `[9, 11, 16]`'
);
} catch (err) {
console.log(err);
}
​
try {
assertSameMembers(
kLargest([29, 17, 9, -1, -3, 11, 2], 6),
[29, 17, 11, 9, 2, -1]
);
​
console.log(
'PASSED: `kLargest([29, 17, 9, -1, -3, 11, 2], 6)` returns `[29, 17, 11, 9, 2, -1]`'
);
} catch (err) {
console.log(err);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?