DEV Community

Discussion on: Interview Qs Decoded - # 1

Collapse
appurist profile image
Paul / Appurist • Edited

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 of second 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:

    for(let i=0; i < arr.length; i++){
        if(arr[i] >= largest){
           second = largest;
           largest = arr[i];
        };
    };