

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Finding the third maximum number in an array
We are required to write a JavaScript function that takes in an array of Numbers. The function should pick and return the third highest number from the array.
The time complexity of our function must not exceed O(n), we have to find the number in single iteration.
Example
const arr = [1, 5, 23, 3, 676, 4, 35, 4, 2]; const findThirdMax = (arr) => { let [first, second, third] = [-Infinity, -Infinity, -Infinity]; for (let el of arr) { if (el === first || el === second || el === third) { continue; }; if (el > first) { [first, second, third] = [el, first, second]; continue; }; if (el > second) { [second, third] = [el, second]; continue; }; if (el > third) { third = el; continue; }; }; return third !== -Infinity ? third : first; }; console.log(findThirdMax(arr));
Output
And the output in the console will be −
23
- Related Questions & Answers
- Finding the third maximum number within an array in JavaScript
- Third smallest number in an array using JavaScript
- Finding unlike number in an array - JavaScript
- Third Maximum Number in C++
- Finding the nth missing number from an array JavaScript
- Finding confusing number within an array in JavaScript
- Finding the maximum in a nested array - JavaScript
- Finding the largest non-repeating number in an array in JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Finding maximum number from two arrays in JavaScript
- Finding the sub array that has maximum sum JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Python - Given an integer list, find the third maximum number if it exists
- Finding the only out of sequence number from an array using JavaScript
Advertisements