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
30
​
def k_largest(nums, k):
# fill in
return k_lgst_nums
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert sorted(k_largest([5, 16, 7, 9, -1, 4, 3, 11, 2], 3)) == sorted(
[9, 11, 16]
)
print(
"PASSED: assert `k_largest([5, 16, 7, 9, -1, 4, 3, 11, 2], 3)` returns `[9, 11, 16]`"
)
​
def test_2(self):
assert sorted(k_largest([29, 17, 9, -1, -3, 11, 2], 6)) == sorted(
[29, 17, 11, 9, 2, -1]
)
print(
"PASSED: assert `k_largest([29, 17, 9, -1, -3, 11, 2], 6)` returns `[29, 17, 11, 9, 2, -1]`"
)
​
​
if __name__ == "__main__":
unittest.main(verbosity=2)
print("Nice job, 2/2 tests passed!")
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.