👋
Welcome to my blog!

Find Three Largest Number

Learn to efficiently identify the three largest numbers in a sequence with this straightforward algorithm.

Find Three Largest Number
Searching
easy

Published At

6/4/2021

Reading Time

~ 2 min read

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

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

Sample Output

js
[18, 141, 541]
js
[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

Solution-1
js
function findThreeLargestNumbers(array) {
  if (array.length < 3) return;
	let arr = []
	
	for (let i = 0; i < 3; i++) {
		let maximum = Math.max(...array)
		let index = array.indexOf(maximum)
		let temp = array.splice(index, 1)[0]
		arr.push(temp)
	}
	return arr.sort((a, b) => a - b)
}
Solution-1
js
function findThreeLargestNumbers(array) {
  if (array.length < 3) return;
	let arr = []
	
	for (let i = 0; i < 3; i++) {
		let maximum = Math.max(...array)
		let index = array.indexOf(maximum)
		let temp = array.splice(index, 1)[0]
		arr.push(temp)
	}
	return arr.sort((a, b) => a - b)
}

🐁

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 🙏

Join My Exclusive Newsletter Community

Step into a world where creativity intersects with technology. By subscribing, you'll get a front-row seat to my latest musings, full-stack development resources, and exclusive previews of future posts. Each email is a crafted experience that includes:

  • In-depth looks at my covert projects and musings to ignite your imagination.
  • Handpicked frontend development resources and current explorations, aimed at expanding your developer toolkit.
  • A monthly infusion of inspiration with my personal selection of quotes, books, and music.

Embrace the confluence of words and wonder, curated thoughtfully and sent straight to your inbox.

No fluff. Just the highest caliber of ideas.