Find Third Largest Element in an Array in Java
Problem
The third largest element is the biggest value in the array after excluding the two largest ones.
Given an array of integers, find its third largest element.
Java Program
public class ThirdLargest {
public static void main(String[] args) {
int[] arr = {12, 45, 3, 68, 22, 7};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE, third = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) { // new overall largest — cascade the other two down
third = second;
second = first;
first = num;
} else if (num > second && num != first) { // new runner-up
third = second;
second = num;
} else if (num > third && num != first && num != second) { // new third place
third = num;
}
}
System.out.println("Third largest: " + third);
}
}Output
Core Logic
Tracking the top three largest values at once, cascading each one down a slot whenever a bigger value arrives, extends the second-largest technique by one more rank.
- 1
first,second, andthirdall start atInteger.MIN_VALUE. - 2A number beating
firstcascades the oldfirstintosecondand the oldsecondintothird, beforefirsttakes the new value. - 3A number that only beats
secondcascades the oldsecondintothirdbeforesecondtakes the new value — as long as it isn't a duplicate offirst. - 4A number that only beats
thirdupdates justthird, as long as it isn't a duplicate offirstorsecond.
[12, 45, 3, 68, 22, 7], the three trackers settle at first=68, second=45, third=22 once the full array has been scanned.Key Point: Each duplicate check has to compare against every rank already filled — a value equal to first or second should never be allowed to also claim third.
Why: A single pass tracks three running values, so the extra memory stays constant regardless of array size.
Key Concepts
Approach 2: Sorting
import java.util.Arrays;
public class ThirdLargestSorted {
public static void main(String[] args) {
int[] arr = {12, 45, 3, 68, 22, 7};
int[] sorted = arr.clone(); // sort a copy, not the caller's original array
Arrays.sort(sorted);
System.out.println("Third largest: " + sorted[sorted.length - 3]); // third-from-last after sorting
}
}
Output
Core Logic
Sorting a copy of the array puts every value in order, so the third largest is simply the third-from-last element.
- 1
arr.clone()copies the array first, so sorting doesn't disturb the caller's original array. - 2
Arrays.sort(sorted)puts the copy into ascending order. - 3
sorted[sorted.length - 3]reads the third-from-last element, which is the third largest value.
[12, 45, 3, 68, 22, 7] gives [3, 7, 12, 22, 45, 68], and the third-from-last element is 22.Key Point: This assumes the top two values are each unique — duplicates among the largest values would shift which position in the sorted array actually holds the 'true' third-largest distinct value.
Why: clone() copies every element into a new array, and sorting that copy costs O(n log n) comparisons.
Key Concepts
Approach 3: Java 8
import java.util.Arrays;
import java.util.Comparator;
public class ThirdLargestStream {
public static void main(String[] args) {
int[] arr = {12, 45, 3, 68, 22, 7};
// Sorts the distinct values descending and skips the top two
int thirdLargest = Arrays.stream(arr)
.boxed()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(2)
.findFirst()
.orElseThrow();
System.out.println("Third largest: " + thirdLargest);
}
}
Output
Core Logic
Sorting the distinct values in descending order and skipping the first two lands directly on the third largest.
- 1
Arrays.stream(arr).boxed()converts theint[]into aStream<Integer>. - 2
.distinct()removes duplicate values, so a repeated top value can't occupy a lower rank's spot. - 3
.sorted(Comparator.reverseOrder())puts the distinct values into descending order. - 4
.skip(2)drops the largest and second largest, and.findFirst()returns whatever comes next — the third largest.
[12, 45, 3, 68, 22, 7], sorting the distinct values descending gives [68, 45, 22, 12, 7, 3]; skipping the first two leaves 22 as the answer.Key Point: Changing .skip(1) to .skip(2) is the only difference from the second-largest version — the same pipeline generalizes cleanly to any rank.
Why: distinct() and sorted() together still perform a comparison sort over the boxed values, and boxing to Integer plus the sort's internal buffer both cost O(n) space.