Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//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"
})`
);
});
@vbUNext
Copy link

vbUNext commented Nov 10, 2020

Quick comments:

  • No test-cases boundary conditions, more variant in test cases are missing
  • Program is not checking for boundary conditions, input sanity check etc.
  • O(nlogn) solution is perfect
  • O(n) logic will not work for negative cases, that is why writing test cases while thinking of boundary conditions are important

@vaibhav-kumar-tokyo
Copy link

vaibhav-kumar-tokyo 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