# findSecondLargest
// Problem 2 - Find second largest within O(n) complexity.
function findSecondLargest(sequence) {
// Write your algorithm here with O(n) time complexity.
if(!Array.isArray(sequence)) return 'Not an Array'
if(sequence.length < 2) return 'Can not find'
if(typeof sequence[0] !== "number") return 'Can not find'
let largest = sequence[0];
let secondLargest = -Infinity;
for(let i=1; i<sequence.length; i++){
// θ₯εΊηΎδΈζ―ζΈεηεΌι£ζεΊι―θͺ€
if (typeof sequence[i] !== "number") return 'Can not find'
if(sequence[i] > largest){
secondLargest = largest
largest = sequence[i]
} else if(sequence[i] < largest && sequence[i] > secondLargest){
secondLargest = sequence[i]
}
}
// eg. [3, 3, 3, 3, 3]
if(secondLargest === -Infinity) return 'Can not find'
return secondLargest;
}
Last updated