Sort by

recency

|

1474 Discussions

|

  • + 0 comments

    function getSecondLargest(nums) { // Complete the function let fun = nums.sort(function(a,b){return b-a}) let rem = [] for (let i = 0;i

    }

  • + 0 comments

    function getSecondLargest(nums) { let maxVal = Math.max(...nums); nums = nums.filter(item => item !== maxVal) let maxVal2 = Math.max(...nums); return maxVal2; }

  • + 0 comments

    function getSecondLargest(nums) { nums.sort((a,b)=>{ return b-a;
    }) for(var i=0; i nums[i+1]) return nums[i+1]; } }

  • + 0 comments

    Simple solution in single loop

    function getSecondLargest(nums) {
        // Complete the function
        let largest = nums[0];
        let secondLargest= nums[0];
        let n= nums.length ;
        
        for(let i=0; i<n; i++){
            if(nums[i]>largest){
                secondLargest=largest;
                largest= nums[i];
            }else if(nums[i]>secondLargest && nums[i]!= largest){
                secondLargest= nums[i];
            }
        }
        return secondLargest;
    }
    
  • + 0 comments

    So, O(n) is the best we could expect here.

    function getSecondLargest(nums) {
        // Complete the function
        let max = -Infinity, sndMax = -Infinity;
        for (let num of nums) {
            if (num > max) {
                sndMax = max;
                max = num;
            } else if (num > sndMax && num !== max) {
                sndMax = num;
            }
        }
        return sndMax;
    }