VOOZH about

URL: https://www.geeksforgeeks.org/dsa/third-largest-element-array-distinct-elements/

⇱ Third largest element in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Third largest element in an array

Last Updated : 24 Apr, 2026

Given an array of n integers, the task is to find the third largest element.

Examples :

Input: arr[] = [2, 4, 1, 3, 5]
Output: 3
Explanation: The third largest element in the array [2, 4, 1, 3, 5] is 3.

Input: arr[] = [10, 2]
Output: -1
Explanation: There are less than three elements in the array, so the third largest element cannot be determined.

Input: arr[] = [5, 5, 5]
Output: 5
Explanation: In the array [5, 5, 5], the third largest element can be considered 5, as there are no other distinct elements.

[Naive Approach] Using Sorting - O(n * log n) Time and O(1) Space

The idea is to sort the array and return the third largest element in the array which will be present at (n-3)'th index.


Output
3

[Expected Approach - 1] Using Three Loops - O(n) Time and O(1) Space

The idea is to iterate the array twice and mark the maximum and second maximum element and then excluding them both find the third maximum element, i.e., the maximum element excluding the maximum and second maximum.

Step by step approach:

  • First, iterate through the array and find maximum.
  • Store this as first maximum along with its index.
  • Now traverse the whole array finding the second max, excluding the maximum element.
  • Finally traverse the array the third time and find the third largest element i.e., excluding the maximum and second maximum.

Output
3

[Expected Approach - 2] Using Single Loop - O(n) Time and O(1) Space

he idea is to traverse the array from start to end and to keep track of the three largest elements up to that index (stored in variables). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array.

Step by step approach: 

  • Create three variables, first, second, third, to store indices of three largest elements of the array. (Initially all of them are initialized to a minimum value).
  • Move along the input array from start to the end.
  • For every index check if the element is larger than first or not. Update the value of first, if the element is larger, and assign the value of first to second and second to third. So the largest element gets updated and the elements previously stored as largest becomes second largest, and the second largest element becomes third largest.
  • Else if the element is larger than the second, then update the value of second, and the second largest element becomes third largest.
  • If the previous two conditions fail, but the element is larger than the third, then update the third.

Output
3

Related Articles:


Comment
Article Tags: