AlgoDaily

K Largest Elements From List

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

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 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)
```js
function kLargest(nums, k) {
	// fill in
  return nums;
}
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →