Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example :
Input: arr[] = {1, 14, 2, 16, 10, 20}
Output: The third Largest element is 14
Explanation: Largest element is 20, second largest element is 16
and third largest element is 14
Input: arr[] = {19, -10, 20, 14, 2, 16, 10}
Output: The third Largest element is 16
Explanation: Largest element is 20, second largest element is 19
and third largest element is 16
Naive Approach: The task is to first find the largest element, followed by the second-largest element and then excluding them both find the third-largest element. The basic 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.
Algorithm:
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
// C program to find third Largest element in an array of
// distinct elements
#include <limits.h>
#include <stdio.h>
voidthirdLargest(intarr[], intarr_size)
{
/* There should be atleast three elements */
if(arr_size < 3) {
printf(" Invalid Input ");
return;
}
// Find first largest element
intfirst = arr[0];
for(inti = 1; i < arr_size; i++)
if(arr[i] > first)
first = arr[i];
// Find second largest element
intsecond = INT_MIN;
for(inti = 0; i < arr_size; i++)
if(arr[i] > second && arr[i] < first)
second = arr[i];
// Find third largest element
intthird = INT_MIN;
for(inti = 0; i < arr_size; i++)
if(arr[i] > third && arr[i] < second)
third = arr[i];
printf("The third Largest element is %d\n", third);
}
/* Driver program to test above function */
intmain()
{
intarr[] = { 12, 13, 1, 10, 34, 16 };
intn = sizeof(arr) / sizeof(arr[0]);
thirdLargest(arr, n);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C++
// C++ program to find third Largest
// element in an array of distinct elements
#include <bits/stdc++.h>
voidthirdLargest(intarr[], intarr_size)
{
/* There should be atleast three elements */
if(arr_size < 3) {
printf(" Invalid Input ");
return;
}
// Find first largest element
intfirst = arr[0];
for(inti = 1; i < arr_size; i++)
if(arr[i] > first)
first = arr[i];
// Find second largest element
intsecond = INT_MIN;
for(inti = 0; i < arr_size; i++)
if(arr[i] > second && arr[i] < first)
second = arr[i];
// Find third largest element
intthird = INT_MIN;
for(inti = 0; i < arr_size; i++)
if(arr[i] > third && arr[i] < second)
third = arr[i];
printf("The third Largest element is %d\n", third);
}
/* Driver program to test above function */
intmain()
{
intarr[] = { 12, 13, 1, 10, 34, 16 };
intn = sizeof(arr) / sizeof(arr[0]);
thirdLargest(arr, n);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to find third
// Largest element in an array
// of distinct elements
classGFG
{
staticvoidthirdLargest(intarr[],
intarr_size)
{
/* There should be
atleast three elements */
if(arr_size < 3)
{
System.out.printf(" Invalid Input ");
return;
}
// Find first
// largest element
intfirst = arr[0];
for(inti = 1;
i < arr_size ; i++)
if(arr[i] > first)
first = arr[i];
// Find second
// largest element
intsecond = Integer.MIN_VALUE;
for(inti = 0;
i < arr_size ; i++)
if(arr[i] > second &&
arr[i] < first)
second = arr[i];
// Find third
// largest element
intthird = Integer.MIN_VALUE;
for(inti = 0;
i < arr_size ; i++)
if(arr[i] > third &&
arr[i] < second)
third = arr[i];
System.out.printf("The third Largest "+
"element is %d\n", third);
}
// Driver code
publicstaticvoidmain(String []args)
{
intarr[] = {12, 13, 1,
10, 34, 16};
intn = arr.length;
thirdLargest(arr, n);
}
}
// This code is contributed
// by Smitha
Python3
# Python 3 program to find
# third Largest element in
# an array of distinct elements
importsys
defthirdLargest(arr, arr_size):
# There should be
# atleast three elements
if(arr_size < 3):
print(" Invalid Input ")
return
# Find first
# largest element
first =arr[0]
fori inrange(1, arr_size):
if(arr[i] > first):
first =arr[i]
# Find second
# largest element
second =-sys.maxsize
fori inrange(0, arr_size):
if(arr[i] > second and
arr[i] < first):
second =arr[i]
# Find third
# largest element
third =-sys.maxsize
fori inrange(0, arr_size):
if(arr[i] > third and
arr[i] < second):
third =arr[i]
print("The Third Largest",
"element is", third)
# Driver Code
arr =[12, 13, 1,
10, 34, 16]
n =len(arr)
thirdLargest(arr, n)
# This code is contributed
# by Smitha
Javascript
<script>
// JavaScript program to find third
// Largest element in an array
// of distinct elements
functionthirdLargest(arr, arr_size)
{
/* There should be
atleast three elements */
if(arr_size < 3)
{
document.write(" Invalid Input ");
return;
}
// Find first
// largest element
let first = arr[0];
for(let i = 1;
i < arr_size ; i++)
if(arr[i] > first)
first = arr[i];
// Find second
// largest element
let second = Number.MIN_VALUE;
for(let i = 0;
i < arr_size ; i++)
if(arr[i] > second &&
arr[i] < first)
second = arr[i];
// Find third
// largest element
let third = Number.MIN_VALUE;
for(let i = 0;
i < arr_size ; i++)
if(arr[i] > third &&
arr[i] < second)
third = arr[i];
document.write("The third Largest "+
"element is ", third);
}
// Driver Code
let arr = [12, 13, 1,
10, 34, 16];
let n = arr.length;
thirdLargest(arr, n);
</script>
C#
// C# program to find third
// Largest element in an array
// of distinct elements
usingSystem;
classGFG
{
staticvoidthirdLargest(int[]arr,
intarr_size)
{
/* There should be
atleast three elements */
if(arr_size < 3)
{
Console.Write(" Invalid Input ");
return;
}
// Find first
// largest element
intfirst = arr[0];
for(inti = 1;
i < arr_size ; i++)
if(arr[i] > first)
first = arr[i];
// Find second
// largest element
intsecond = -int.MaxValue;
for(inti = 0;
i < arr_size ; i++)
if(arr[i] > second &&
arr[i] < first)
second = arr[i];
// Find third
// largest element
intthird = -int.MaxValue;
for(inti = 0;
i < arr_size ; i++)
if(arr[i] > third &&
arr[i] < second)
third = arr[i];
Console.Write("The third Largest "+
"element is "+ third);
}
// Driver code
publicstaticvoidMain()
{
int[]arr = {12, 13, 1,
10, 34, 16};
intn = arr.Length;
thirdLargest(arr, n);
}
}
// This code is contributed by Smitha
PHP
<?php
// PHP program to find third
// Largest element in an array
// of distinct elements
functionthirdLargest($arr, $arr_size)
{
/* There should be atleast
three elements */
if($arr_size< 3)
{
echo" Invalid Input ";
return;
}
// Find first largest element
$first= $arr[0];
for($i= 1; $i< $arr_size; $i++)
if($arr[$i] > $first)
$first= $arr[$i];
// Find second largest element
$second= PHP_INT_MIN;
for($i= 0; $i< $arr_size; $i++)
if($arr[$i] > $second&&
$arr[$i] < $first)
$second= $arr[$i];
// Find third largest element
$third= PHP_INT_MIN;
for($i= 0; $i< $arr_size; $i++)
if($arr[$i] > $third&&
$arr[$i] < $second)
$third= $arr[$i];
echo"The third Largest element is ",
$third,"\n";
}
// Driver Code
$arr= array(12, 13, 1,
10, 34, 16);
$n= sizeof($arr);
thirdLargest($arr, $n);
// This code is contributed by m_kit
?>
Output
The third Largest element is 13
Complexity Analysis:
Time Complexity: O(n). As the array is iterated thrice and is done in a constant time
Space complexity: O(1). No extra space is needed as the indices can be stored in constant space.
Efficient Approach: The problem deals with finding the third largest element in the array in a single traversal. The problem can be cracked by taking help of a similar problem- finding the second maximum element. So 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). So after traversing the whole array, the variables would have stored the indices (or value) of the three largest elements of the array.
Algorithm:
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.
Print the value of third after traversing the array from start to end
C++
// C++ program to find third
// Largest element in an array
#include <bits/stdc++.h>
voidthirdLargest(intarr[], intarr_size)
{
/* There should be atleast three elements */
if(arr_size < 3)
{
printf(" Invalid Input ");
return;
}
// Initialize first, second and third Largest element
intfirst = arr[0], second = INT_MIN, third = INT_MIN;
// Traverse array elements to find the third Largest
for(inti = 1; i < arr_size ; i ++)
{
/* If current element is greater than first,
then update first, second and third */
if(arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second */
elseif(arr[i] > second)
{
third = second;
second = arr[i];
}
/* If arr[i] is in between second and third */
elseif(arr[i] > third)
third = arr[i];
}
printf("The third Largest element is %d\n", third);
}
/* Driver program to test above function */
intmain()
{
intarr[] = {12, 13, 1, 10, 34, 16};
intn = sizeof(arr)/sizeof(arr[0]);
thirdLargest(arr, n);
return0;
}
Java
// Java program to find third Largest element in an array
classGFG {
staticvoidthirdLargest(intarr[], intarr_size) {
/* There should be atleast three elements */
if(arr_size < 3) {
System.out.printf(" Invalid Input ");
return;
}
// Initialize first, second and third Largest element
intfirst = arr[0], second = Integer.MIN_VALUE,
third = Integer.MIN_VALUE;
// Traverse array elements to find the third Largest
for(inti = 1; i < arr_size; i++) {
/* If current element is greater than first,
then update first, second and third */
if(arr[i] > first) {
third = second;
second = first;
first = arr[i];
} /* If arr[i] is in between first and second */
elseif(arr[i] > second) {
third = second;
second = arr[i];
} /* If arr[i] is in between second and third */
elseif(arr[i] > third) {
third = arr[i];
}
}
System.out.printf("The third Largest element is %d\n", third);
}
/* Driver program to test above function */
publicstaticvoidmain(String []args) {
intarr[] = {12, 13, 1, 10, 34, 16};
intn = arr.length;
thirdLargest(arr, n);
}
}
//This code is contributed by 29AjayKumar
Python3
# Python3 program to find
# third Largest element in
# an array
importsys
defthirdLargest(arr, arr_size):
# There should be
# atleast three elements
if(arr_size < 3):
print(" Invalid Input ")
return
# Initialize first, second
# and third Largest element
first =arr[0]
second =-sys.maxsize
third =-sys.maxsize
# Traverse array elements
# to find the third Largest
fori inrange(1, arr_size):
# If current element is
# greater than first,
# then update first,
# second and third
if(arr[i] > first):
third =second
second =first
first =arr[i]
# If arr[i] is in between
# first and second
elif(arr[i] > second):
third =second
second =arr[i]
# If arr[i] is in between
# second and third
elif(arr[i] > third):
third =arr[i]
print("The third Largest",
"element is", third)
# Driver Code
arr =[12, 13, 1,
10, 34, 16]
n =len(arr)
thirdLargest(arr, n)
# This code is contributed
# by Smitha
Javascript
<script>
// JavaScript program to find third
// Largest element in an array
functionthirdLargest(arr, arr_size)
{
/* There should be atleast three elements */
if(arr_size < 3)
{
document.write(" Invalid Input ");
return;
}
// Initialize first, second and third Largest element
varfirst = arr[0], second = -1000000000, third = -1000000000;
// Traverse array elements to find the third Largest
for(vari = 1; i < arr_size ; i ++)
{
/* If current element is greater than first,
then update first, second and third */
if(arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second */
elseif(arr[i] > second)
{
third = second;
second = arr[i];
}
/* If arr[i] is in between second and third */
elseif(arr[i] > third)
third = arr[i];
}
document.write("The third Largest element is "+ third);
}
/* Driver program to test above function */
vararr = [12, 13, 1, 10, 34, 16];
varn = arr.length;
thirdLargest(arr, n);
</script>
C#
// C# program to find third Largest element in an array
usingSystem;
classGFG {
staticvoidthirdLargest(int[] arr, intarr_size)
{
/* There should be atleast three elements */
if(arr_size < 3)
{
Console.Write(" Invalid Input ");
return;
}
// Initialize first, second and third Largest element
intfirst = arr[0], second = int.MinValue,
third = int.MinValue;
// Traverse array elements to find the third Largest
for(inti = 1; i < arr_size; i++)
{
/* If current element is greater than first,
then update first, second and third */
if(arr[i] > first) {
third = second;
second = first;
first = arr[i];
}
/* If arr[i] is in between first and second */
elseif(arr[i] > second) {
third = second;
second = arr[i];
}
/* If arr[i] is in between second and third */
elseif(arr[i] > third) {
third = arr[i];
}
}
Console.Write("The third Largest element is "+ third);
}
/* Driver program to test above function */
publicstaticvoidMain() {
int[] arr = {12, 13, 1, 10, 34, 16};
intn = arr.Length;
thirdLargest(arr, n);
}
}
// This code is contributed
// by Ita_c
PHP
<?php
// PHP program to find third
// Largest element in an array
functionthirdLargest($arr, $arr_size)
{
/* There should be atleast
three elements */
if($arr_size< 3)
{
echo" Invalid Input ";
return;
}
// Initialize first, second and
// third Largest element
$first= $arr[0];
$second= PHP_INT_MIN;
$third= PHP_INT_MIN;
// Traverse array elements to
// find the third Largest
for($i= 1; $i< $arr_size; $i++)
{
/* If current element is greater
than first, then update first,
second and third */
if($arr[$i] > $first)
{
$third= $second;
$second= $first;
$first= $arr[$i];
}
/* If arr[i] is in between
first and second */
elseif($arr[$i] > $second)
{
$third= $second;
$second= $arr[$i];
}
/* If arr[i] is in between
second and third */
elseif($arr[$i] > $third)
$third= $arr[$i];
}
echo"The third Largest element is ",
$third;
}
// Driver Code
$arr= array(12, 13, 1,
10, 34, 16);
$n= sizeof($arr);
thirdLargest($arr, $n);
// This code is contributed by jit_t
?>
Output
The third Largest element is 13
Complexity Analysis:
Time Complexity: O(n). As the array is iterated once and is done in a constant time
Space complexity: O(1). No extra space is needed as the indices can be stored in constant space.
Another method: Using Slicing
Here, we are using slicing method, to extract 3rd largest number.
First we will sort the array then we will extract the 3rd largest element using slicing.
C++
#include <bits/stdc++.h>
usingnamespacestd;
intthirdLargest(intarr[], intarr_size)
{
// if array size is less than 3,
// then it will give invalid input
if(arr_size < 3)
{
cout<<" Invalid Input"<<endl;
return0;
}
else
{
// here we are sorting the array
// return 3rd largest element
sort(arr,arr+arr_size);
returnarr[arr_size-3];
}
}
/* Driver program to test above function */
intmain()
{
intarr[] = {12, 13, 1, 10, 34, 16};
intn = sizeof(arr)/sizeof(arr[0]);
cout<<thirdLargest(arr, n)<<endl;
return0;
}
Java
// Java implementation
importjava.util.Arrays;
classMain {
publicstaticintthirdLargest(int[] arr)
{
intarr_size = arr.length;
// if array size is less than 3,
// then it will give invalid input
if(arr_size < 3) {
System.out.println("Invalid Input");
return0;
}
else{
// here we are sorting the array
// return 3rd largest element
Arrays.sort(arr);
returnarr[arr_size - 3];
}
}
/* Driver program to test above function */
publicstaticvoidmain(String[] args)
{
// Input taken
int[] arr = { 12, 13, 1, 10, 34, 16};
System.out.println(thirdLargest(arr));
}
}
Python3
# Python3 program to find
# third Largest element in
# an array
defthirdLargest(arr, arr_size):
if(arr_size < 3): #if array size is less than 3,
#then it will give invalid input
print(" Invalid Input ")
return
else:
arr=sorted(arr) #here we are sorting the array
returnarr[-3] #return 3rd largest element
# Driver Code
arr =[12, 13, 1, 10, 34, 16]
arr_size =len(arr)
print(thirdLargest(arr, arr_size))
C#
usingSystem;
classMainClass {
publicstaticintthirdLargest(int[] arr)
{
intarr_size = arr.Length;
// if array size is less than 3,
// then it will give invalid input
if(arr_size < 3) {
Console.WriteLine("Invalid Input");
return0;
}
else{
// here we are sorting the array
// return 3rd largest element
Array.Sort(arr);
returnarr[arr_size - 3];
}
}
/* Driver program to test above function */
publicstaticvoidMain(string[] args)
{
// Input taken
int[] arr = { 12, 13, 1, 10, 34, 16 };
Console.WriteLine(thirdLargest(arr));
}
}
Javascript
functionthirdLargest(arr) {
let arr_size = arr.length;
// if array size is less than 3,
// then it will give invalid input
if(arr_size < 3) {
console.log("Invalid Input");
return0;
}
else
{
// here we are sorting the array
// return 3rd largest element
arr.sort(function(a, b) {
returna - b;
});
returnarr[arr_size - 3];
}
}
// Driver program to test above function
let arr = [12, 13, 1, 10, 34, 16];
console.log(thirdLargest(arr));
Output
13
Time complexity: O(nlogn). where n is the length of the array. Auxiliary space: O(1)
?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p
Exercise Problem: Extend the above solution to find the third largest when array may have duplicates. For example, if the input array is {10, 5, 15, 5, 15, 10, 1, 1}, then output should be 5. The extended solution should also work in one traversal.
This article is contributed by Vidhi Jindal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute.@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article’s discussion tab.
You will be notified via email once the article is available for improvement.
Thank you for your valuable feedback!
Please Login to comment...