There are several testcases that would not not pass.
in case [0,1] -> 0 is the second largest, but function returns ' '.
in case [1, 0] -> 0 again is the second largest, but the function will return 1.
in case [1,1,1,0] -> same as in the previous testcase.
This happens because of comparison of 0 with an empty string.
' ' === 0 // false
' ' > 0 // false
' ' < 0 // false
The small change that I would do:
Sort the array.
If the array is not empty, take its first element as a potential largest and second.
let largest = arr[0];
let second = arr[0];
You know that arr[0] element exists for sure if array is not empty.
Sorting will allow you to start with the smallest element whatever it is and find the second largest.
Small note for other solutions:
You cannot just sort an array and take a second element from the end ;)
in case of [0,1,2,2,2,2] code will return 2. You also need to make numbers unique.
This challenge also tests how creative you can be in your testcases and the ability to think what can potentially break your code.
How about checking array is valid (as an numeric array which length > 0) via:
if (!Array.isArray(array) || !array.length || array.some(isNaN)) {
return ("Not a valid array")
}
Regarding the 0 comparison, how about:
let max = -Infinity, second = -Infinity
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hi Cat!
Amazing solution!
There are several testcases that would not not pass.
in case [0,1] -> 0 is the second largest, but function returns ' '.
in case [1, 0] -> 0 again is the second largest, but the function will return 1.
in case [1,1,1,0] -> same as in the previous testcase.
This happens because of comparison of 0 with an empty string.
' ' === 0 // false
' ' > 0 // false
' ' < 0 // false
The small change that I would do:
You know that arr[0] element exists for sure if array is not empty.
Sorting will allow you to start with the smallest element whatever it is and find the second largest.
Small note for other solutions:
You cannot just sort an array and take a second element from the end ;)
in case of [0,1,2,2,2,2] code will return 2. You also need to make numbers unique.
This challenge also tests how creative you can be in your testcases and the ability to think what can potentially break your code.
Ooooh got it. Darn it, HackerRank, for giving me a false-positive. ;____;
I'll refactor the code above and credit you! Thanks Lia! You da best.
How about checking array is valid (as an numeric array which length > 0) via:
if (!Array.isArray(array) || !array.length || array.some(isNaN)) {
return ("Not a valid array")
}
Regarding the 0 comparison, how about:
let max = -Infinity, second = -Infinity