Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Second Largest Number

Easy
0/40
Average time to solve is 23m
profile
Contributed by
678 upvotes
Asked in company
Samsung

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.
Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1 :
4
3 4 5 2
Sample Output 1 :
4 3
Explanation For Sample Input 1 :
The second largest element after 5 is 4 only, and the second smallest element after 2 is 3.
Sample Input 2 :
5
4 5 3 6 7
Sample Output 2 :
6 4
Expected Time Complexity:
O(n), Where ‘n’ is the size of an input array ‘a’.
Constraints:
2 ≤ 'n' ≤ 10^5
0 ≤ 'a'[i] ≤ 10^9

Time limit: 1 sec


Hints:
1. Sort the array.
2. More efficiently, can you use the largest and smallest elements to find the required elements?
Approaches (2)
Naive 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]}
Time Complexity

O(n * Log(n)), where ‘n’ is the size of the array ‘a’.
 

As we are sorting the array, it will take the O(n * Log(n)) time.
 

Hence, the time complexity is O(n * Log(n)).

Space Complexity

O(1).

 

As we are using constant extra space.

 

Hence, the space complexity is O(1).

Code Solution
(100% EXP penalty)
Second Largest Number
All tags
Sort by
Search icon

Interview problems

O(n) - Second largest & Second smallest

 vector<int> getSecondOrderElements(int n, vector<int> a) {
   // Write your code here.
   int max = a[0], max2 = -1;
   int min = a[0], min2 = INT_MAX;
   for(int i=1;i<n;i++)
   {
       if(max<a[i])
       {
           max2 = max;
           max = a[i];
       }
       else if(max2<a[i])
           max2 = a[i];
       if(min>a[i])
       {
           min2= min;
           min = a[i];
       }
       else if(min2>a[i])
           min2 = a[i];
   }
   vector<int> ans;
   ans.push_back(max2);
   ans.push_back(min2);
   return ans;
}
7 views
0 replies
0 upvotes

Interview problems

Java Optimal Solution | Most Easy

  1. Sorting: The Arrays.sort(a) method sorts the array in ascending order.
  2. Accessing Elements: After sorting, the second smallest element is at index 1, and the second largest element is at index n-2.
  3. Return Value: The method returns an array containing the second largest and second smallest elements.

 

public class Solution {

    public static int[] getSecondOrderElements(int n, int []a) {

        // Write your code here.

        Arrays.sort(a);

 

        int s_largest = a[n-2];

        int s_smallest = a[1];

        return new int[]{s_largest,s_smallest};

    }

}

40 views
0 replies
1 upvote

Interview problems

simple cpp approach by using 4 variables

Initialization: Set maxi and mxi to INT_MIN for the largest and second largest, and mini and mni to INT_MAX for the smallest and second smallest.

Single Pass: Iterate through the array:

  • Update maxi and mxi based on comparisons with the current element.
  • Update mini and mni similarly.

Return Result: After processing all elements, return a vector containing mxi (second largest) and mni (second smallest).

Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(1)

This method efficiently finds the second largest and second smallest elements in one traversal without extra space

 

 

code:

 

vector<int> getSecondOrderElements(int n, vector<int> arr) {

    int maxi = INT_MIN, mxi = INT_MIN, mini = INT_MAX, mni = INT_MAX;

    for(int i=0;i<n;i++) {

        if(arr[i] > maxi) {

            mxi = maxi;

            maxi = arr[i];

        } else if(arr[i] > mxi && arr[i] != maxi) {

            mxi = arr[i];

        }

 

        if(arr[i] < mini) {

            mni = mini;

            mini = arr[i];

        } else if(arr[i] < mni && arr[i] != mini) {

            mni = arr[i];

        }

    }

    return {mxi,mni};

}

 

83 views
0 replies
1 upvote

Interview problems

cpp solution using stl

vector<int> getSecondOrderElements(int n, vector<int> a) {

    // Write your code here.

    sort(a.begin(),a.end());

    return{a[n-2],a[1]};

    

}

183 views
0 replies
1 upvote

Interview problems

Python Code - TC = O(n)

  • Converts the input array to a set to remove duplicates, ensuring unique elements.
  • Finds the smallest and largest elements using min() and max() functions.
  • Removes the smallest and largest elements from the set.
  • If fewer than two elements remain, returns the smallest and largest.
  • Finds the second smallest and second largest from the remaining elements.
  • Time Complexity: O(n), where n is the size of the input array.
  • Space Complexity: O(n) due to the conversion of the array into a set, which requires additional space proportional to the input size. def getSecondOrderElements(n,a):

    if len(a) < 2:

        return

    list1 = set(a)

    num1 = min(list1)

    num2 = max(list1)

    list1.remove(num1)

    list1.remove(num2)

 

    if len(list1) < 1:  

        return [num1,num2]

    else:

        c = min(list1)

        d = max(list1)

        return [d,c]

    

94 views
0 replies
0 upvotes

Interview problems

SECOND LARGEST AND SMALLEST (JAVA OPTIMAL SOLLUTION)

public class Solution {

    public static int[] getSecondOrderElements(int n, int []a) {

        // Write your code here.

        int largest = secondLargest(a, n);

        int smallest = second_smallest(a, n);

        return new int[] {largest, smallest};

    }

 

    public static int secondLargest(int a[], int n){

        int largest = a[0];

        int sec_largest = Integer.MIN_VALUE;

        for(int i=1; i<n; i++){

            if (largest < a[i]) {

                sec_largest = largest;

                largest = a[i];

            } else if( largest > a[i] && sec_largest < a[i]){

                sec_largest = a[i];

            }

        }

        return sec_largest;

    }

 

    public static int second_smallest (int a[], int n){

        int smallest = a[0];

        int sec_smallest = Integer.MAX_VALUE;

        for(int i=1; i<n; i++){

            if (smallest > a[i]) {

                sec_smallest = smallest;

                smallest = a[i];

            } else if( smallest != a[i] && sec_smallest > a[i]){

                sec_smallest = a[i];

            }

        }

        return sec_smallest;

    }

}

361 views
0 replies
0 upvotes

Interview problems

CPP

vector<int> getSecondOrderElements(int n, vector<int> a) {

    // Write your code here.

    int smallest = INT_MAX, secondSmallest = INT_MAX;

    int largest = INT_MIN, secondLargest = INT_MIN;

 

    //largest , smallest 

    for(int i = 0; i < n;i++){

        smallest = min(smallest,a[i]);

        largest = max(largest,a[i]);

    }

 

    //secsmallestv , seclargest

    for(int i = 0;i < n; i++){

        if(a[i] <secondSmallest && a[i] != smallest){

            secondSmallest = a[i];

        }

        if(a[i] > secondLargest && a[i] != largest){

            secondLargest = a[i];

        }

    }

    return {secondLargest,secondSmallest};

}

/*

Test Case

//smallesst , Largest

‘a’ = [1, 2, 3, 4, 5] n-1

samllest 1

largest 5

 

// SecSmallest , secLargest

stp 1 - 1 < INT_MAX & secSmll is INT_MAX

stp 2 - 2 < INT_MAX & 2 != 1 SecSmall = 2

return secSamlllest 

 

stp 1 - 1 < INT_MIN & 1 != 5 SecLar = 1

stp 2 - 2 < 1 & 2 != 5 seclar = 2

stp 3 - 3 < 2 & 3!=5 Secalr = 3

stp 4 - 4 < 3 & 4 != 5 secLar = 4

stp 5 - 5 < 4 & 5!=5 

return seclargest is 4

 

Edge Case 

int arr{}

if(arr.empty()){

    cout<<"Error : Array is empty "<<endl;

    return INT_MIN;

}

 

int arr{10,10,10,10}

Seclar and secsamll - 10 ,10 

*/

 

206 views
0 replies
0 upvotes

Interview problems

How do you print second Largest and second Smallest using cpp in a simple manner?

In cpp, we have a default function called sort, that sorts all elements in ascending order, so the last elemnt is obviously the greatest and last but 1 is second greatest, the first element is smallest and second element is second smallest. 

The array position of second element is arr[1] and index position of last but 1 element is arr[n-2]

Using this just write the logic. You are good to go:)

 

CODE:-

 

vector<int>getSecondOrderElement(int n, vector <int> a){

sort(a.begin(), a.end());

int secsmall=a[1];

int secLargest=a[n-2];

return {secLargest,secsmall};

}

45 views
0 replies
0 upvotes

Interview problems

java easy solution with and without sorting

import java.util.Arrays;

 

public class Solution {

    public static int[] getSecondOrderElements(int n, int []a) {

        // Write your code here.

        Arrays.sort(a);

        int b[]=new int[2];

        b[0]=a[n-2];

        b[1]=a[1];

        return b;

    }

}

 

 

import java.util.Arrays;


 

public class Solution {

    public static int[] getSecondOrderElements(int n, int []a) {

        // Write your code here.

        //Arrays.sort(a);

        int b[]=new int[2];

        int small=Integer.MAX_VALUE;

        int S_small=Integer.MAX_VALUE;  //Second small

        int max=Integer.MIN_VALUE;

        int S_max=Integer.MIN_VALUE;   //Second max

        for(int i=0;i<n;i++){

            if(a[i]<small){

                S_small=small;

                small=a[i];

            }

            else if (a[i] < S_small && a[i] != small) {        //where small=3,S_small=5,a[i]=4

                S_small = a[i];

            }

 

            if(a[i]>max){

                S_max=max;

                max=a[i];

            }else if (a[i] > S_max && a[i] != max) {

                S_max = a[i];

            }

        }

        b[0]=S_max;

        b[1]=S_small;

        return b;

    }

}

202 views
0 replies
1 upvote

Interview problems

PYTHON SOLUTION [ Beginner friendly]

1.sort the array 

2.get the second largest and second small element

3.create new empty list

4. add the second largest and second smallest element in it

5.return the list to get result

def getSecondOrderElements(n: int,  a: [int]) -> [int]:

    a.sort()

    H = a[-2]

    A = a[1]

    list = []

    list.append(H)

    list.append(A)

    return list

    

python

85 views
0 replies
1 upvote
Full screen
Console