### Find Second Largest Element in Array - The Coding Shala

Home >> Programming >> Find Second Largest Element

Hey there, welcome back to another post. In this post, we will learn how to find the second largest element in the array in Java.

# Find Second Largest Element in Array

Find the second largest element in the given array if exist else return -1.

Example 1:

```Input:
[1, 6, 2, 7, 10, 8, -11]
Output:
8
```

By using the below methods we can find the second largest element in the array.

## Find Second Largest Element Java Solution Using Single Iteration

We can find the largest and second-largest elements in the array by using a single iteration. The approach is below.

Approach / Explanation

1. If the given array size if less than 2 then there is no second largest element so return -1.
2. Create two variables first and second to store the largest and second-largest elements and the initial value is Integer.MIN_VALUE.
3. Traverse the array and check if the current element is greater than the largest element then update both the first and second element.
4. If the current element is between the largest and second-largest element and it's not equal to the largest element then we just need to update the second largest element.
5. Return the second largest element.

Time Complexity: O(n)

Space Complexity: O(1)

Java Program:

```/**
* https://www.thecodingshala.com/
*/

public class Main {

public static int printSecondLargest(int[] arr) {
// size is less than 2
if (arr.length < 2) {
return Integer.MIN_VALUE;```
```        }

int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;

for (int i = 0; i < arr.length; i++) {
// if arr[i] is bigger than first and second
// update both
if (arr[i] > first) {
second = first;
first = arr[i];
}

// if arr[i] is between first and second then update second
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}

return second;
}

public static void main(String[] args) {
// int[] arr = {3, 6, -1, 0, 55, 23, 56, 80, -96};
// int[] arr = {1};
// int[] arr = {1, 2, 2};
int[] arr = {1, 1, 1, 1};

// print array
System.out.println("The array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

int ele = printSecondLargest(arr);
if (ele == Integer.MIN_VALUE) {
System.out.println("There is no second largest element in the array");
} else {
System.out.println("The second largest element is: " + ele);
}
}
}
```

Output:

```The array is:
1 1 1 1
There is no second largest element in the array
```

Other Posts You May Like