Hello everyone! Welcome to the first in a series! I'm going to try to explain a common software engineering interview question to better understand...
For further actions, you may consider blocking this person and/or reporting abuse
Sure good point:
Just for the sake of brevity, but not improved performance:
Daaamn that’s slick. 👌🏾👌🏾👌🏾
Yeah but I bet yours is faster :)
The initializers should probably be undefined since the function will return the wrong result if the array consists of fewer than 2 items or if all items in the array consist of the same value.
Gotta watch out for those edge cases!
My solution using using the Ramda library
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.
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
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.
As a learning lesson, this example could be improved:
First, there's a bug in that it doesn't handle cases like
[2, 5, 10, 9, 10, 7]
where the numbers aren't unique. (I double-checked, uniqueness was not part of your Params description above.) In that case, the code above will return 9, even though it's clearly not the second-largest.Second, if you fix that by using
>=
in the first test, the second one isn't even needed. The storing ofsecond
in the first test takes care of the second largest, even if there's only one element in the array.So the
for
loop could be simplified to just:Why not return arr.sortDescending()[1] ?
Subscribed!
if(arr.length > 1)
return arr.sort((a,b)=> {return b-a})[1]
Good point! Let me try that out and I'll fix it up. :) Thanks Sebastian!
Well the problem was toooo simple.
You may want to make it recursive for multi-dimensional arrays