Mark As Completed Discussion

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.

Description

Can you find more than one approach to this problem?

Constraints

  • Length of the array <= 100000
  • The array will contain values between -1000000000 and 1000000000
  • The final answer will always fit in the integer range
  • Expected time complexity : O(n logk) where k 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?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's our guided, illustrated walk-through.

How do I use this guide?