DSA - Find second largest in array

Given an array Arr of size N, print second largest distinct element from an array.

Input: N = 6 Arr[] = {12, 35, 1, 10, 34, 1}
Output: 34 *
Explanation:* The largest element of the array is 35 and the second largest element is 34.

Example 2:

Input: N = 3 Arr[] = {10, 5, 10} *
Output:* 5 *
Explanation:* The largest element of the array is 10 and the second largest element is 5.

2 Likes

Different ways to do this

Most easy way- Sort the array using library function and return the second last element. But here the time complexity would be `nlogn`

But we can do it in O(n)

  • Make two variables largest and secondLargest
  • Iterate through array, if the current element is greater than largest , do the below steps-
secondLargest=largest;
largest=currentElement;
  • If the currentElement is greater than secondLargest then only update secondLargest
secondLargest=currentElement;

At last you would have secondLargest