Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active November 23, 2020 13:59
Show Gist options
  • Save ShilpiMaurya/58fbf5f86adce0edb3b8fa4ca5a5d962 to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/58fbf5f86adce0edb3b8fa4ca5a5d962 to your computer and use it in GitHub Desktop.
//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"
})`
);
});
@vbkmr
Copy link

vbkmr commented Nov 21, 2020

There is one O(n) solution tho.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment