Problem
Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.
Similar problem - Find smallest and second smallest elements in an array
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Sorting
A simple solution will be first sort the array in descending order and then return the second element from the sorted array. The time complexity of this solution is O(nlogn).
Method 2 - Two pass
A Better Solution is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n).
Method 3 - One pass solution
A more Efficient Solution can be to find the second largest element in a single traversal.
Algorithm
- Takes an integer array
arras input. - Checks if the array size is less than 2. If so, it returns -1.
- Initializes
largestandsecondLargestwith the minimum possible integer value (Integer.MIN_VALUE). - Iterates through the array using a single loop.
- Within the loop, compares the current element
arr[i]with bothlargestandsecondLargest.- If
arr[i]is greater thanlargest, it becomes the newlargestand the previouslargestbecomes thesecondLargest. - If
arr[i]is greater than the currentsecondLargestbut not equal to the currentlargest, it becomes the newsecondLargest.
- If
Edge case
We should return -1 if secondLargest remains Integer.MIN_VALUE after the loop (indicating all elements are equal).
Code
| |
Complexity
- Time complexity: O(n)
- Auxiliary Space : O(1)