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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read