Third largest element in an array - GeeksforGeeks

Third largest element in an array

Last Updated : 15 Oct, 2026

Given an array, arr[] of positive integers. Find the third largest element in it. Return -1 if the third largest element is not found.

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.

Try It Yourself
redirect icon

[Naive Approach] 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.

C++
#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;

int thirdLargest(vector<int> &arr)
{
    int n = arr.size();

    // If the array has less than 3 elements, return -1
    if (n < 3)
    {
        return -1;
    }

    // Sort the array
    sort(arr.begin(), arr.end());

    // Return the third largest element
    return arr[n - 3];
}

int main()
{
    vector<int> arr = {2, 4, 1, 3, 5};
    cout << thirdLargest(arr) << endl;

    return 0;
}
Java
import java.util.*;

public class GFG {
    public static int thirdLargest(List<Integer> arr)
    {
        int n = arr.size();

        // If the array has less than 3 elements, return -1
        if (n < 3) {
            return -1;
        }

        // Sort the list
        Collections.sort(arr);

        // Return the third largest element
        return arr.get(n - 3);
    }

    public static void main(String[] args)
    {
        List<Integer> arr
            = new ArrayList<>(Arrays.asList(2, 4, 1, 3, 5));

        System.out.println(thirdLargest(arr));
    }
}
Python
def thirdLargest(arr):
    n = len(arr)
    
    if n < 3:
        return -1
    # Sort the array 
    arr.sort()
    
    # Return the third largest element 
    return arr[n - 3]

if __name__ == "__main__":
    arr = [2, 4, 1, 3, 5]
    print(thirdLargest(arr))
C#
using System;

class GFG {
    static int thirdLargest(int[] arr)
    {
        int n = arr.Length;

        // If the array has less than 3 elements, return -1
        if (n < 3) {
            return -1;
        }

        // Sort the array
        Array.Sort(arr);

        // Return the third largest element
        return arr[n - 3];
    }

    static void Main()
    {
        int[] arr = { 2, 4, 1, 3, 5 };
        Console.WriteLine(thirdLargest(arr));
    }
}
JavaScript
function thirdLargest(arr)
{
    let n = arr.length;

    // If the array has less than 3 elements, return -1
    if (n < 3) {
        return -1;
    }

    // Sort the array
    arr.sort((a, b) => a - b);

    // Return the third largest element
    return arr[n - 3];
}

// Driver Code
let arr = [ 2, 4, 1, 3, 5 ];
console.log(thirdLargest(arr));

Output
3

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

The idea is to iterate the array twice and mark the maximum and second maximum elements.

Iterate third time, excluding the above found 2, find the third maximum element.

Working of 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.
C++
#include <iostream>
#include <vector>
using namespace std;

int thirdLargest(vector<int> &arr)
{
    int n = arr.size();

    // If the array has less than 3 elements, return -1
    if (n < 3)
    {
        return -1;
    }

    // Pass 1: Find the first maximum element and remember its index
    int first = -1;
    int first_idx = -1;
    for (int i = 0; i < n; i++)
    {
        if (arr[i] > first)
        {
            first = arr[i];
            first_idx = i;
        }
    }

    // Pass 2: Find the second max element by skipping the EXACT index of the first
    int second = -1;
    int second_idx = -1;
    for (int i = 0; i < n; i++)
    {
        if (i == first_idx)
            continue;

        if (arr[i] > second)
        {
            second = arr[i];
            second_idx = i;
        }
    }

    // Pass 3: Find the third largest element by skipping the indices of first and second
    int third = -1;
    for (int i = 0; i < n; i++)
    {
        if (i == first_idx || i == second_idx)
            continue;

        if (arr[i] > third)
        {
            third = arr[i];
        }
    }

    // Return the third largest element
    return third;
}

int main()
{
    vector<int> arr = {2, 4, 1, 3, 5};
    cout << thirdLargest(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static int thirdLargest(List<Integer> arr)
    {
        int n = arr.size();

        // If the array has less than 3 elements, return -1
        if (n < 3) {
            return -1;
        }

        // Pass 1: Find the first maximum element and
        // remember its index
        int first = -1;
        int first_idx = -1;
        for (int i = 0; i < n; i++) {
            if (arr.get(i) > first) {
                first = arr.get(i);
                first_idx = i;
            }
        }

        // Pass 2: Find the second max element by skipping
        // the EXACT index of the first
        int second = -1;
        int second_idx = -1;
        for (int i = 0; i < n; i++) {
            if (i == first_idx)
                continue;

            if (arr.get(i) > second) {
                second = arr.get(i);
                second_idx = i;
            }
        }

        // Pass 3: Find the third largest element by
        // skipping the indices of first and second
        int third = -1;
        for (int i = 0; i < n; i++) {
            if (i == first_idx || i == second_idx)
                continue;

            if (arr.get(i) > third) {
                third = arr.get(i);
            }
        }

        // Return the third largest element
        return third;
    }

    public static void main(String[] args)
    {
        List<Integer> arr = Arrays.asList(2, 4, 1, 3, 5);
        System.out.println(thirdLargest(arr));
    }
}
Python
def thirdLargest(arr):
    n = len(arr)
    
    if n < 3:
        return -1
        
    # Find the first maximum element.
    first = -1
    first_idx = float('-inf')
    for i in range(n):
        if arr[i] > first:
            first = arr[i]
            first_idx = i
    
    # Find the second max element.
    second = -1
    second_idx = float('-inf')
    for i in range(n):
        if i == first_idx:
            continue
        
        if arr[i] > second:
            second = arr[i]
            second_idx = i
    
    # Find the third largest element.
    third = -1
    third = float('-inf')
    for i in range(n):
        if i == first_idx or i == second_idx:
            continue
        
        if arr[i] > third:
            third = arr[i]
    
    # Return the third largest element 
    return third

if __name__ == "__main__":
    arr = [2, 4, 1, 3, 5]
    print(thirdLargest(arr))
C#
using System;

class GFG {
    static int thirdLargest(int[] arr)
    {
        int n = arr.Length;

        // If the array has less than 3 elements, return -1
        if (n < 3) {
            return -1;
        }

        // Pass 1: Find the first maximum element and
        // remember its index
        int first = -1;
        int first_idx = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] > first) {
                first = arr[i];
                first_idx = i;
            }
        }

        // Pass 2: Find the second max element by skipping
        // the EXACT index of the first
        int second = -1;
        int second_idx = -1;
        for (int i = 0; i < n; i++) {
            if (i == first_idx)
                continue;

            if (arr[i] > second) {
                second = arr[i];
                second_idx = i;
            }
        }

        // Pass 3: Find the third largest element by
        // skipping the indices of first and second
        int third = -1;
        for (int i = 0; i < n; i++) {
            if (i == first_idx || i == second_idx)
                continue;

            if (arr[i] > third) {
                third = arr[i];
            }
        }

        // Return the third largest element
        return third;
    }

    static void Main()
    {
        int[] arr = { 2, 4, 1, 3, 5 };
        Console.WriteLine(thirdLargest(arr));
    }
}
JavaScript
function thirdLargest(arr)
{
    let n = arr.length;

    // If the array has less than 3 elements, return -1
    if (n < 3) {
        return -1;
    }

    // Pass 1: Find the first maximum element and remember
    // its index
    let first = -1;
    let first_idx = -1;
    for (let i = 0; i < n; i++) {
        if (arr[i] > first) {
            first = arr[i];
            first_idx = i;
        }
    }

    // Pass 2: Find the second max element by skipping the
    // EXACT index of the first
    let second = -1;
    let second_idx = -1;
    for (let i = 0; i < n; i++) {
        if (i === first_idx)
            continue;

        if (arr[i] > second) {
            second = arr[i];
            second_idx = i;
        }
    }

    // Pass 3: Find the third largest element by skipping
    // the indices of first and second
    let third = -1;
    for (let i = 0; i < n; i++) {
        if (i === first_idx || i === second_idx)
            continue;

        if (arr[i] > third) {
            third = arr[i];
        }
    }

    // Return the third largest element
    return third;
}

// Driver code
let arr = [ 2, 4, 1, 3, 5 ];
console.log(thirdLargest(arr));

Output
3

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

The 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).

After traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array.

Working of Approach:

  • Create three variables, first, second, and third, to store the largest, second largest, and third largest elements, respectively. Initially, all three are set to minus infinity.
  • Traverse the input array from the beginning to the end.
  • For each element, check if it is greater than first. If so, update third with second, second with first, and first with the current element.
  • Otherwise, if the element is greater than second, update third with second and second with the current element.
  • If neither of the above conditions holds, but the element is greater than third, update third with the current element.
  • Finally, return third as the third largest element.
C++
#include <climits>
#include <iostream>
#include <vector>

using namespace std;

int thirdLargest(vector<int> &arr)
{
    int n = arr.size();

    int first = INT_MIN, second = INT_MIN, third = INT_MIN;

    // If length of array is less than 3, return -1
    if (n < 3)
    {
        return -1;
    }

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

        // If arr[i] is greater than first,
        // set third to second, second to
        // first and first to arr[i].
        if (arr[i] > first)
        {
            third = second;
            second = first;
            first = arr[i];
        }

        // If arr[i] is greater than second,
        // set third to second and second
        // to arr[i].
        else if (arr[i] > second)
        {
            third = second;
            second = arr[i];
        }

        // If arr[i] is greater than third,
        // set third to arr[i].
        else if (arr[i] > third)
        {
            third = arr[i];
        }
    }

    // Return the third largest element
    return third;
}

int main()
{
    vector<int> arr = {2, 4, 1, 3, 5};
    cout << thirdLargest(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    static int thirdLargest(List<Integer> arr)
    {
        int n = arr.size();

        int first = Integer.MIN_VALUE,
            second = Integer.MIN_VALUE,
            third = Integer.MIN_VALUE;

        // If length of array is less than 3, return -1
        if (n < 3) {
            return -1;
        }

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

            // If arr[i] is greater than first,
            // set third to second, second to
            // first and first to arr[i].
            if (arr.get(i) > first) {
                third = second;
                second = first;
                first = arr.get(i);
            }

            // If arr[i] is greater than second,
            // set third to second and second
            // to arr[i].
            else if (arr.get(i) > second) {
                third = second;
                second = arr.get(i);
            }

            // If arr[i] is greater than third,
            // set third to arr[i].
            else if (arr.get(i) > third) {
                third = arr.get(i);
            }
        }

        // Return the third largest element
        return third;
    }

    public static void main(String[] args)
    {
        List<Integer> arr = Arrays.asList(2, 4, 1, 3, 5);
        System.out.println(thirdLargest(arr));
    }
}
Python
def thirdLargest(arr):
    n = len(arr)
    
    first, second, third = float('-inf'), float('-inf'), float('-inf')
    
    if n < 3:
        return -1
    
    for i in range(n):
        
        # If arr[i] is greater than first,
        # set third to second, second to 
        # first and first to arr[i].
        if arr[i] > first:
            third = second
            second = first
            first = arr[i]
        
        # If arr[i] is greater than second, 
        # set third to second and second 
        # to arr[i].
        elif arr[i] > second:
            third = second
            second = arr[i]
        
        # If arr[i] is greater than third,
        # set third to arr[i].
        elif arr[i] > third:
            third = arr[i]
    
    # Return the third largest element 
    return third

if __name__ == "__main__":
    arr = [2, 4, 1, 3, 5]
    print(thirdLargest(arr))
C#
using System;

class GFG {
    static int thirdLargest(int[] arr)
    {
        int n = arr.Length;

        int first = int.MinValue, second = int.MinValue,
            third = int.MinValue;

        // If length of array is less than 3, return -1
        if (n < 3) {
            return -1;
        }

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

            // If arr[i] is greater than first,
            // set third to second, second to
            // first and first to arr[i].
            if (arr[i] > first) {
                third = second;
                second = first;
                first = arr[i];
            }

            // If arr[i] is greater than second,
            // set third to second and second
            // to arr[i].
            else if (arr[i] > second) {
                third = second;
                second = arr[i];
            }

            // If arr[i] is greater than third,
            // set third to arr[i].
            else if (arr[i] > third) {
                third = arr[i];
            }
        }

        // Return the third largest element
        return third;
    }

    static void Main()
    {
        int[] arr = { 2, 4, 1, 3, 5 };
        Console.WriteLine(thirdLargest(arr));
    }
}
JavaScript
function thirdLargest(arr)
{
    let n = arr.length;

    let first = -Infinity, second = -Infinity,
        third = -Infinity;

    // If length of array is less than 3, return -1
    if (n < 3) {
        return -1;
    }

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

        // If arr[i] is greater than first,
        // set third to second, second to
        // first and first to arr[i].
        if (arr[i] > first) {
            third = second;
            second = first;
            first = arr[i];
        }

        // If arr[i] is greater than second,
        // set third to second and second
        // to arr[i].
        else if (arr[i] > second) {
            third = second;
            second = arr[i];
        }

        // If arr[i] is greater than third,
        // set third to arr[i].
        else if (arr[i] > third) {
            third = arr[i];
        }
    }

    // Return the third largest element
    return third;
}

// Driver Code
let arr = [ 2, 4, 1, 3, 5 ];
console.log(thirdLargest(arr));

Output
3
Comment