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.
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.
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.
4
3 4 5 2
4 3
The second largest element after 5 is 4 only, and the second smallest element after 2 is 3.
5
4 5 3 6 7
6 4
O(n), Where ‘n’ is the size of an input array ‘a’.
2 ≤ 'n' ≤ 10^5
0 ≤ 'a'[i] ≤ 10^9
Time limit: 1 sec
1. Sort the array.
2. More efficiently, can you use the largest and smallest elements to find the required elements?
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:
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)).
O(1).
As we are using constant extra space.
Hence, the space complexity is O(1).