Last active
November 23, 2020 13:59
-
-
Save ShilpiMaurya/58fbf5f86adce0edb3b8fa4ca5a5d962 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//How do you find the second highest number in an integer array? | |
const secondHighestNumber = arr => { | |
if (!Array.isArray(arr) || !arr.length) { | |
return null; | |
} | |
let largestNum = Math.max(...arr); | |
arr.splice(arr.indexOf(largestNum), 1); | |
let secondHighestNum = Math.max(...arr); | |
return secondHighestNum; | |
}; | |
//Time-complexity: O(n) | |
//Test cases | |
const testCase = [ | |
{ input: [], output: null }, | |
{ input: "engimatic", output: null }, | |
{ input: [1, 2, 3, 4, 5, 7, 6], output: 6 }, | |
{ input: [11, 24, 31, 40, 15, 32, 16], output: 32 }, | |
{ input: [-1, 0, 1, 2], output: 1 }, | |
{ input: [-1, -2, -3, -4, -5], output: -2 } | |
]; | |
testCase.forEach(({ input, output }, index) => { | |
console.log( | |
`TEST CASE:${index} (${input}):(${ | |
secondHighestNumber(input) === output ? "success" : "failure" | |
})` | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick comments: