![]() |
VOOZH | about |
Given an array of n integers, the task is to find the third largest element.
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.
Table of Content
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.
3
The 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.
Step by step approach:
3
he 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.
Step by step approach:
3
Related Articles: