Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the second largest number in array

I have an array of three element like [31,23,12] and I want to find the second largest element and its related position without rearranging the array.

Example :

array = [21,23,34]

Second_largest = 23;

Position is = 1;

like image 711
sachin yadav Avatar asked Dec 06 '17 23:12

sachin yadav


People also ask

How do you find the second largest number in an array C++?

Take input a stream of n integer elements, find the second largest element present. The given elements can contain duplicate elements as well. If only 0 or 1 element is given, the second largest should be INT_MIN ( - 2^31 ).

How do I find the second largest number in an array in Excel?

In its simplest form, LARGE will return the "Nth largest" value in a range. For example, the formula: = LARGE ( B4:B13 , 2 ) will return the 2nd largest value in the range B4:B13 which, in the example above, is the number 9.


20 Answers

Make a clone of your original array using .slice(0) like :

var temp_arr = arr.slice(0);

Then sor it so you get the second largest value at the index temp_arr.length - 2 of your array :

temp_arr.sort()[temp_arr.length - 2]

Now you could use indexOf() function to get the index of this value retrieved like :

arr.indexOf(second_largest_value);

var arr = [23, 21, 34, 34];
var temp_arr = [...new Set(arr)].slice(0); //clone array
var second_largest_value = temp_arr.sort()[temp_arr.length - 2];
var index_of_largest_value = arr.indexOf(second_largest_value);

console.log(second_largest_value);
console.log(index_of_largest_value);
like image 92
Zakaria Acharki Avatar answered Oct 18 '22 09:10

Zakaria Acharki


Using ES6 Set and Array.from

const secondLargest = (arr) => Array.from([...new Set(arr)]).sort((a,b) => b-a)[1]

Above function removes duplicate elements using Set and returns the second largest element from the sorted array.

like image 42
Sathishkumar Rakkiyasamy Avatar answered Oct 18 '22 10:10

Sathishkumar Rakkiyasamy


You could create a copy of the original array using spread and sort() it. From you'd just get the second to last number from the array and use indexOf to reveal it's index.

const array = [21,23,34];
const arrayCopy = [...array];

const secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));

Alternatively you can use concat to copy the array if compatibility is an issue:

var array = [21, 23, 34];
var arrayCopy = [].concat(array);

var secondLargestNum = arrayCopy.sort()[arrayCopy.length - 2]

console.log(array.indexOf(secondLargestNum));
like image 22
Carl Edwards Avatar answered Oct 18 '22 08:10

Carl Edwards


This way is the most verbose, but also the most algorithmically efficient. It only requires 1 pass through the original array, does not require copying the array, nor sorting. It is also ES5 compliant, since you were asking about supportability.

var array = [21,23,34];

var res = array.reduce(function (results, curr, index) {
    if (index === 0) {
        results.largest = curr;
        results.secondLargest = curr;
        results.indexOfSecondLargest = 0;
        results.indexOfLargest = 0;
    }
    else if (curr > results.secondLargest && curr <= results.largest) {
        results.secondLargest = curr;
        results.indexOfSecondLargest = index;
    }
    else if (curr > results.largest) {
        results.secondLargest = results.largest;
        results.largest = curr;
        results.indexOfSecondLargest = results.indexOfLargest;
        results.indexOfLargest = index;
    }
    return results;
}, {largest: -Infinity, secondLargest: -Infinity, indexOfLargest: -1, indexOfSecondLargest: -1});

console.log("Second Largest: ", res.secondLargest);
console.log("Index of Second Largest: ", res.indexOfSecondLargest);
like image 32
mhodges Avatar answered Oct 18 '22 10:10

mhodges


I tried to make the answer as simple as possible here, you can it super simple

function getSecondLargest(nums) {
    var flarge = 0;
    var slarge = 0;
    for (var i = 0; i < nums.length; i++) { 
            if (flarge < nums[i]) {
                slarge = flarge;
                flarge = nums[i];
            } else if (nums[i] > slarge) { 
                slarge = nums[i]

            }
        }
        return slarge; 
}

Its fully logical ,there is no array sort or reverse here, you can also use this when values are duplicate in aray.

like image 41
Dhruv Thakkar Avatar answered Oct 18 '22 10:10

Dhruv Thakkar


function getSecondLargest(nums) {
nums.sort(function(x,y){
       return y-x;
    });
for(var j=1; j < nums.length; j++)
 {
    if(nums[j-1] !== nums[j])
    {
         return nums[j];
    }
 }
}
getSecondLargest([1,2,3,4,5,5]);

OUTPUT: 4

This method will also take care of the multiple occurrence of a number in the array. Here, we are first sorting the array and then ignoring the same number and returning our answer.

like image 32
Ayush Aryan Avatar answered Oct 18 '22 10:10

Ayush Aryan


I recently came across this problem, but wasn't allowed to use looping. I managed to get it working using recursion and since no one else suggested that possibility, I decided to post it here. :-)

let input = [29, 75, 12, 89, 103, 65, 100, 78, 115, 102, 55, 214]

const secondLargest = (arr, first = -Infinity, second = -Infinity, firstPos = -1, secondPos = -1, idx = 0) => {
    arr = first === -Infinity ? [...arr] : arr;

    const el = arr.shift();
    if (!el) return { second, secondPos }

    if (el > first) {
        second = first;
        secondPos = firstPos;
        first = el;
        firstPos = idx;
    } if (el < first && el > second) {
        second = el;
        secondPos = idx;
    }  

    return secondLargest(arr, first, second, firstPos, secondPos, ++idx);
}

console.log(secondLargest(input));
//  {
//    second: 115,
//    secondPos: 8
//  }

Hope this helps someone in my shoes some day.

like image 22
Andrew Senner Avatar answered Oct 18 '22 09:10

Andrew Senner


Simple recursive function to find the n-largest number without permutating any array:

EDIT: Also works in case of multiple equal large numbers.

let array = [11,23,34];

let secondlargest = Max(array, 2);
let index = array.indexOf(secondlargest);

console.log("Number:", secondlargest ,"at position", index);

function Max(arr, nth = 1, max = Infinity) {
  let large = -Infinity;
  for(e of arr) {
    if(e > large && e < max ) {
      large = e;
    } else if (max == large) {
      nth++;
    }
  }
  if(nth==0) return max;
  return Max(arr, nth-1, large);
}
like image 20
toeffe3 Avatar answered Oct 18 '22 08:10

toeffe3


Just to get 2nd largest number-

arr = [21,23,34];
secondLargest = arr.slice(0).sort(function(a,b){return b-a})[1]; 

To get 2nd largest number with index in traditional manner-

arr = [20,120,111,215,54,78];
max = -Infinity;
max2 = -Infinity;
indexMax = -Infinity;
index2 = -Infinity;

for(let i=0; i<arr.length; i++) {
    if(max < arr[i]) {
        index2 = indexMax;
        indexMax = i;
        max2 = max;
        max = arr[i];
    } else if(max2 < arr[i]) {
        index2 = i;
        max2 = arr[i];
    }
}

console.log(`index: ${index2} and max2: ${max2}`);
like image 23
Chang Avatar answered Oct 18 '22 10:10

Chang


I have tried to solve without using the inbuilt function.

var arr = [1,2, -3, 15, 77, 12, 55];
var highest = 0, secondHighest = 0;
// OR var highest = arr[0], secondHighest = arr[0];

for(var i=0; i<arr.length; i++){
  if(arr[i] > highest){
    secondHighest = highest;
    highest = arr[i]; 
  }

  if(arr[i] < highest && arr[i] > secondHighest){
    secondHighest = arr[i];
  }
}

console.log('>> highest number : ',highest); // 77
console.log('>> secondHighest number : ',secondHighest); // 55
like image 42
Dere Sagar Avatar answered Oct 18 '22 09:10

Dere Sagar


var arr = [21,23,34];
var output = getSecondLargest(arr);

document.getElementById("output").innerHTML = output;

function getSecondLargest(nums) {
    if (nums.length == 0){
         return undefined;
    }
    nums.sort((a,b) => b-a);
    var newArr = [...new Set(nums)];
    return newArr[1];
}
<p id="output"></p>
like image 37
Vaibhav Singh Avatar answered Oct 18 '22 09:10

Vaibhav Singh


function getSecondLargest(nums) {
  const sortedArray = new Set(nums.sort((a, b) => b - a)).values();
  sortedArray.next();

  return sortedArray.next().value;
}

console.log(getSecondLargest([1, 2, 4, 4, 3]));
like image 34
Mustafa Elsherbeny Avatar answered Oct 18 '22 09:10

Mustafa Elsherbeny


//Suggest making unique array before checking largest value in the array

    function getSecondLargest(arr) {
        let uniqueChars = [...new Set(arr)];
       
        let val=Math.max(...uniqueChars);
       
        let arr1 = arr.filter(function(item) {
        return item !== val;
        })
    
        let num=Math.max(...arr1);
        return num;
    }
    
     function main() {
         const n = +(readLine());
         const nums = readLine().split(' ').map(Number);
        
         console.log(getSecondLargest(nums));
    }
like image 30
keshari abeysinghe Avatar answered Oct 18 '22 10:10

keshari abeysinghe


Here the code will give the second largest number and the index of it

const a = [1, 2, 3, 4, 6, 7, 7, 8, 15]

a.sort((a,b)=>a-b) //sorted small to large
const max = Math.max(...a)
const index = a.indexOf(max)
const s = {secondLargest:a[index-1],index:index-1}
console.log(s)
like image 22
ramVermilion Avatar answered Oct 18 '22 09:10

ramVermilion


var elements = [21,23,34]

var largest = -Infinity

// Find largest 
for (var i=0; i < elements.length; i++) {
  if (elements[i] > largest) largest = elements[i]
}

var second_largest = -Infinity
var second_largest_position = -1

// Find second largest
for (var i=0; i < elements.length; i++) {
  if (elements[i] > second_largest && elements[i] < largest) {
    second_largest = elements[i]
    second_largest_position = i
  }
}

console.log(second_largest, second_largest_position)
like image 20
stdob-- Avatar answered Oct 18 '22 08:10

stdob--


function getSecondLargest(nums) {
  let arr = nums.slice();//create a copy of the input array
  let max = Math.max(...arr);//find the maximum element
  let occ = 0;
    for(var i = 0 ; i < arr.length ; i++)
    {
        if(arr[i] == max)
        {
            occ = occ +1;//count the occurrences of maximum element
        }
    }

    let sortedArr =arr.sort(function(x, y) { return x > y; } );//sort the array

    for(var i = 1 ; i <= occ ; i++){
        sortedArr.pop()//remove the maximum elements from the sorted array
    }


    return Math.max(...sortedArr);//now find the largest to get the second largest



}
like image 26
Dhana Avatar answered Oct 18 '22 08:10

Dhana


I write the most simple function with O(n) complexity using two variables max and secondMax with simple swapping logic.

function getSecondLargest(nums) {
  let max = 0, secondMax = 0;
  nums.forEach((num) => {
    if (num > max) {
        secondMax = max;
        max = num;
    } else if (num != max && num > secondMax) secondMax = num;
  });
  return secondMax;
}
like image 34
Syed Kashan Ali Avatar answered Oct 18 '22 08:10

Syed Kashan Ali


here you can also deal with if the second largest or largest number is repeated

var nums =[2,3,6,6,5]; 
function getSecondLargest(nums) {
    let secondlargets;
nums.sort(function(a, b){return a - b});
// all elements are in the accesindg order
// [1,2,3,5,6,6]
var highest;
// that is the last sorted element
highest = nums[nums.length-1];

nums.pop();
// through above statment we are removing the highest element 
for(let i =0;i<nums.length-1;i++){
  if(nums[nums.length-1]==highest){
    /* here we remove gives this as conditon because might be the hiesht 
     had more indecis as we have in this question index(5) &index(6)
    so remove the element till all positon have elemnt excepts the highest */
     nums.pop()        
 }
else{
    
    return nums[nums.length-1]
/*  our array is already sorted and after removing thew highest element */
        }

    } 

} 
    
like image 21
MUKUL RANA Avatar answered Oct 18 '22 10:10

MUKUL RANA


Please find a simple solution, without using inbuild functions:

Time complexity is O(n)

function secondLargest(arr) {
        let prev = [0]
        let i =1;
        let largest =0;
        while(i<arr.length){
            let current = arr[i];
            if(current > largest ) {
                largest = current;
                prev = arr[i-1];
            } else if (current > prev && current < largest) {
                prev = current
            }
            i++;
        }
        return prev;
    }
    
    let arr = [1,2,3,41,61,10,3,5,23];
    console.log(secondLargest(arr));
like image 31
ashish siddhu Avatar answered Oct 18 '22 08:10

ashish siddhu


Here is a simple solution using .sort() and new Set()

const array = [21, 23, 34, 34];

function getSecondLargest(arr){ 
   return list = [...new Set(arr)].sort((a, b) => b - a)[1]
};

getSecondLargest(array);
like image 31
norbekoff Avatar answered Oct 18 '22 09:10

norbekoff