• + 0 comments

    function getSecondLargest(nums) {

    //! Solution 1
    // const distinctNums = [...new Set(nums)];
    
    // distinctNums.sort((a,b)=> a-b)
    
    // return distinctNums[distinctNums.length -2]
    
    //! Solution 2
    
    let largest = nums[0],
        secondLargest = nums[0];
    
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] > largest) {
            secondLargest = largest;
            largest = nums[i];
        } else if (nums[i] > secondLargest && nums[i] < largest) {
            secondLargest = nums[i];
        }
    }
    
    return secondLargest;
    

    }