Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active November 23, 2020 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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"
})`
);
});
@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

@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