Find Three Largest Number

A corgi smiling happily

Write a function that takes in an array of at least three integers and, without sorting the input array, returns a sorted array of the three largest integers in the input array.

The function should return duplicate integers if necessary; for example, it should return [10, 10, 12] for an input array of [10, 5, 9, 10, 12].

Sample Input

1array = [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7]

Sample Output

1[18, 141, 541]

Hints

Hint 1

Can you keep track of the three largest numbers in an array as you traverse the input array?

Hint 2

Following the suggestion in Hint #1, try traversing the input array and updating the three largest numbers if necessary by shifting them accordingly.

Optimal Space & Time Complexity

O(n) time | O(1) space - where n is the length of the input array

1function findThreeLargestNumbers(array) {
2 if (array.length < 3) return;
3 let arr = []
4
5 for (let i = 0; i < 3; i++) {
6 let maximum = Math.max(...array)
7 let index = array.indexOf(maximum)
8 let temp = array.splice(index, 1)[0]
9 arr.push(temp)
10 }
11 return arr.sort((a, b) => a - b)
12}

🐁

Do you have any questions, or simply wish to contact me privately? Don’t hesitate to shoot me a DM on Twitter.

Have a wonderful day.
Abhishek 🙏

Subscribe to my newsletter

Get email from me about my ideas, full-stack development resources, tricks and tips as well as exclusive previews of upcoming articles.

No spam. Just the highest quality ideas you’ll find on the web.