|
| 1 | +package Third_Largest_Element; |
| 2 | +/* |
| 3 | + Given an array, arr of positive integers. Find the third largest element in it. |
| 4 | + Return -1 if the third largest element is not found. |
| 5 | +
|
| 6 | + Naive Approach (by sorting): |
| 7 | + The idea is to sort the array in Ascending order and return the third largest element |
| 8 | + in the array which will be present at (n-3)’th index. |
| 9 | + (OR) |
| 10 | + Sort the array in Descending order and return the 2nd index element which will be the third largest element. |
| 11 | +
|
| 12 | + Test Cases: 1110 / 1120 passed on GeekForGeeks |
| 13 | +
|
| 14 | + Examples: |
| 15 | + Input: arr[] = [2, 4, 1, 3, 5] |
| 16 | + Output: 3 |
| 17 | + Explanation: The third largest element in the array [2, 4, 1, 3, 5] is 3. |
| 18 | +
|
| 19 | + Input: arr[] = [10, 2] |
| 20 | + Output: -1 |
| 21 | + Explanation: There are less than three elements in the array, so the third largest element cannot be determined. |
| 22 | +*/ |
| 23 | + |
| 24 | +// Time Complexity: O(n * log n) --> depends on the sorting algo used |
| 25 | +// Space Complexity: O(1) |
| 26 | + |
| 27 | +public class Naive_Approach_By_Sorting { |
| 28 | + int thirdLargest(int arr[]) { |
| 29 | + int n = arr.length; |
| 30 | + |
| 31 | + /* |
| 32 | + * If there are less than 3 elements in the array, then the third largest |
| 33 | + * element cannot be determined. |
| 34 | + */ |
| 35 | + if (n < 3) { |
| 36 | + return -1; |
| 37 | + } else { |
| 38 | + // Sort the array in descending order and return the 3rd index element |
| 39 | + for (int i = 1; i < n; i++) { |
| 40 | + int key = arr[i]; |
| 41 | + int j = i - 1; |
| 42 | + |
| 43 | + while ((j >= 0) && (arr[j] < key)) { |
| 44 | + arr[j + 1] = arr[j]; |
| 45 | + j--; |
| 46 | + } |
| 47 | + |
| 48 | + arr[j + 1] = key; |
| 49 | + } |
| 50 | + |
| 51 | + /* |
| 52 | + * Return the Third largest element which is the third element (2nd index) of |
| 53 | + * the sorted array |
| 54 | + */ |
| 55 | + return arr[2]; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments