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

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**

- If the given array size if less than 2 then there is no second largest element so return -1.
- Create two variables first and second to store the largest and second-largest elements and the initial value is Integer.MIN_VALUE.
- Traverse the array and check if the current element is greater than the largest element then update both the first and second element.
- 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.
- 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**

- Min Steps in Infinite Grid
- Maximum Absolute Difference
- Check if n and its Double exist in the Array
- Simple XML Validator
- New Year Chaos

Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

## Comments

## Post a Comment