Sort by

recency

|

1471 Discussions

|

  • + 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;
    }
    
  • + 0 comments

    Hello! I tried to not use the native sorting function, to really exercise the coding. Since it's a tutorial with the purpose of practicing the language, I've implemented the quicksort:

        let lastIndex = nums.length - 1;
        let sortedNums = quickSort(nums, 0, lastIndex);
        let largest = sortedNums[lastIndex];
        let secondLargest;
        for(let x = lastIndex; x >= 0; x--) {
            if (largest === sortedNums[x])
                continue;
            else {
                secondLargest = sortedNums[x];
                break;
            }         
        }
        return secondLargest;
    }
    function partition(arr, low, high) {
            let pivot = arr[high];
            let i = low - 1; 
            for(let j = low; j <= high-1; j++){
                if(pivot > arr[j]){              
                    i++;                
                    swap(arr, i, j);   
                }
            }
            
            swap(arr, i+1, high); 
            return i+1; 
    }
    function quickSort(arr, low, high) {
            if (high > low) {
                let pi = partition(arr, low, high);
                quickSort(arr, low, pi - 1); 
                quickSort(arr, pi+1, high); 
            } 
            return arr;
    }   
    function swap(arr, i, j) {
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
    }
    
  • + 0 comments

    function getSecondLargest(nums) { // Complete the function let sortedNums = Array.from(new Set(nums)).sort((a, b) => (b-a));

    //sorted nums;
    return sortedNums[1];
    

    }

  • + 0 comments
    function getSecondLargest(nums) {
        const uniqueNums = nums.filter((value, idx, self)=> self.indexOf(value) === idx);
        return uniqueNums.sort((a,b)=>b-a)[1];
    }