Last Updated: 13 Oct, 2022

Second Largest Number

Easy
Asked in companies
SamsungDXC TechnologyCognizant Technology Solutions India Pvt Ltd

Problem statement

You have been given an array ‘a’ of ‘n’ unique non-negative integers.


Find the second largest and second smallest element from the array.


Return the two elements (second largest and second smallest) as another array of size 2.


Example :
Input: ‘n’ = 5, ‘a’ = [1, 2, 3, 4, 5]
Output: [4, 2]

The second largest element after 5 is 4, and the second smallest element after 1 is 2.
Input Format:
The first line will contain the integer ‘n’, the number of elements in the array ‘a’, and the next line will contain the ‘n’ spaced integers in the array elements. 
Output Format:
Print two elements, the second largest and the second smallest element, from the array.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function.

Approaches

01 Approach

Approach
 

In this approach, we will sort the given array, and the answer will be the second and second last element as the second smallest and second largest elements respectively.
 

Algorithm: 
 

  • Sort the given array ‘a’
  • Return {a[n - 2], a[1]}

02 Approach

Approach
 

First, we will traverse the array and will find the smallest and largest elements. Then we will travel again and will find the element just greater than the smallest element and the element just smaller than the largest element. The elements found after words are the required answer.
 

Algorithm: 
 

  • Initialize the variables ‘small = INT_MAX’, ‘large = INT_MIN’, ‘secondSmall = INT_MAX’ and ‘secondLarge = INT_MIN’.
  • Iterate over the array ‘a’ with iterator ‘i’
    • Set ‘large = max(large, a[i])’ and ‘small = min(small, a[i])’
  • Iterate from 0 to ‘n’ with iterator ‘i’
    • If ‘a[i] < secondSmall && a[i] != small’ then update ‘secondSmall = a[i]’
    • If ‘a[i] > secondLarge && a[i] != large’ then update ‘secondLarge = a[i]’
  • Return ‘{secondLarge, secondSmall}’