Java Program for Third largest element in an array of distinct elements
Last Updated :
03 Jan, 2022
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.
Java
// Java program to find third
// Largest element in an array
// of distinct elements
class GFG
{
static void thirdLargest(int arr[],
int arr_size)
{
/* There should be
atleast three elements */
if (arr_size < 3)
{
System.out.printf(" Invalid Input ");
return;
}
// Find first
// largest element
int first = arr[0];
for (int i = 1;
i < arr_size ; i++)
if (arr[i] > first)
first = arr[i];
// Find second
// largest element
int second = Integer.MIN_VALUE;
for (int i = 0;
i < arr_size ; i++)
if (arr[i] > second &&
arr[i] < first)
second = arr[i];
// Find third
// largest element
int third = Integer.MIN_VALUE;
for (int i = 0;
i < arr_size ; i++)
if (arr[i] > third &&
arr[i] < second)
third = arr[i];
System.out.printf("The third Largest " +
"element is %d
", third);
}
// Driver code
public static void main(String []args)
{
int arr[] = {12, 13, 1,
10, 34, 16};
int n = arr.length;
thirdLargest(arr, n);
}
}
// This code is contributed
// by Smitha
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
Java
// Java program to find third Largest element in an array
class GFG {
static void thirdLargest(int arr[], int arr_size) {
/* There should be atleast three elements */
if (arr_size < 3) {
System.out.printf(" Invalid Input ");
return;
}
// Initialize first, second and third Largest element
int first = arr[0], second = Integer.MIN_VALUE,
third = Integer.MIN_VALUE;
// Traverse array elements to find the third Largest
for (int 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 */
else if (arr[i] > second) {
third = second;
second = arr[i];
} /* If arr[i] is in between second and third */
else if (arr[i] > third) {
third = arr[i];
}
}
System.out.printf("The third Largest element is %d
", third);
}
/* Driver program to test above function */
public static void main(String []args) {
int arr[] = {12, 13, 1, 10, 34, 16};
int n = arr.length;
thirdLargest(arr, n);
}
}
//This code is contributed by 29AjayKumar
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.
Please refer complete article on
Third largest element in an array of distinct elements for more details!
Similar Reads
Java Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu
2 min read
Java Program to Find Largest Element in an Array Finding the largest element in an array is a common programming task. There are multiple approaches to solve it. In this article, we will explore four practical approaches one by one to solve this in Java.Example Input/Output:Input: arr = { 1, 2, 3, 4, 5}Output: 5Input: arr = { 10, 3, 5, 7, 2, 12}Ou
4 min read
Java Program to Sort the Elements of an Array in Descending Order Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
Java Program for Number of local extrema in an array You are given an array on n-elements. An extrema is an elements which is either greater than its both of neighbors or less than its both neighbors. You have to calculate the number of local extrema in given array. Note : 1st and last elements are not extrema.Examples : Input : a[] = {1, 5, 2, 5} Out
2 min read
Java Program to Find 2 Elements in the Array such that Difference Between them is Largest An array is the most efficient data structure that is designed to store and access a group of objects. Given an array of integers, our task is to find out two elements from that array such that the difference between them is the maximum. We will be discussing two approaches: By comparing and checkin
4 min read
Java Program for Maximize elements using another array Given two arrays with size n, maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first array). The order of appeara
3 min read
Java Program for Leaders in an array Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example in the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the arr
3 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Remove Duplicate Elements From the Array Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele
6 min read