Table of contents
1.
Introduction
2.
Find Second Largest Element in an Array
3.
Constraints
4.
Approach 1 (Simple Solution)
4.1.
Implementation 
4.2.
C++
4.3.
Java
4.4.
Python
5.
Approach 2 (Better Solution)
5.1.
C++
5.2.
Java
5.3.
Python
6.
Approach 3 (Efficient Solution)
6.1.
C++
6.2.
Java
6.3.
Python
7.
Frequently Asked Questions
7.1.
What if the array contains duplicate elements?
7.2.
Can we solve this problem using sorting?
7.3.
What if the array has less than two elements?
8.
Conclusion
Last Updated: Aug 24, 2024
Medium

Program to Find Second Largest Element in an Array

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

An array is a collection of elements of the same data type. When you work with arrays, you may often need to find the second-largest element. This is a common programming problem that tests your understanding of arrays & logical thinking skills. 

Program to Find Second Largest Element in an Array

In this article, we will discuss different approaches to find the second largest element in an array, with the help of proper codes and will check their complexities also.

Find Second Largest Element in an Array

Finding the second largest element in an array means identifying the element that is smaller than the largest element but larger than all other elements. For example, if we have an array [5, 2, 8, 1, 9], the second largest element would be 8. This problem can be solved using various approaches, each with its own time & space complexity. 


Now, let’s discuss an example to understand this in a better manner : 


Let's consider an array arr = [10, 5, 8, 20, 15]. In this array, the largest element is 20, and the second largest element is 15. Our task is to write a program that takes an array as input and returns the second largest element.

Input: arr = [10, 5, 8, 20, 15]
Output: 15

 

Here's another example:

Input: arr = [12, 35, 1, 10, 34, 1]
Output: 34

 

In this example, the largest element is 35, and the second largest element is 34.

Let’s understand how it works

To find the second largest element in an array, we need to compare each element with the current largest and second largest elements. Let's walk through the example arr = [10, 5, 8, 20, 15]:

1. Initialize two variables, `largest` and `secondLargest`, to store the largest and second largest elements. Set `largest` to the first element (arr[0] = 10) and `secondLargest` to a small value, like INT_MIN.
 

2. Iterate through the array starting from the second element (index 1):

  • If the current element is greater than `largest`, update `secondLargest` to `largest` and `largest` to the current element.
     
  • If the current element is greater than `secondLargest` but not equal to `largest`, update `secondLargest` to the current element.
     

3. After the iteration, `secondLargest` will hold the second largest element.
 

In the given example:

  • Index 1: 5 is not greater than `largest` (10), so no update.
     
  • Index 2: 8 is not greater than `largest` (10), so no update.
     
  •  Index 3: 20 is greater than `largest` (10), so `secondLargest` becomes 10, and `largest` becomes 20.
     
  • Index 4: 15 is not greater than `largest` (20), but it is greater than `secondLargest` (10), so `secondLargest` becomes 15.

 

Finally, `secondLargest` holds the value 15, which is the second largest element in the array.

Constraints

Before we look into the different approaches to solve this problem, let's discuss the constraints that our solution should follow :
 

1. The array should contain at least two elements. If the array has only one element, there is no second largest element.
 

2. The array may contain duplicate elements. In such cases, we consider the second occurrence of the largest element as the second largest element.
 

3. The array may contain elements in any order, so we cannot assume that the elements are sorted.
 

4. The solution should have a time complexity better than O(n^2), where n is the number of elements in the array. This means we should avoid nested loops that compare each element with every other element.
 

5. The solution should be space-efficient, using only a constant amount of extra space.

Approach 1 (Simple Solution)

The simple solution is to iterate through the array twice. In the first iteration, we find the largest element. In the second iteration, we find the largest element that is smaller than the element found in the first iteration. 

Let’s see the step-by-step algorithm:

1. Initialize a variable `largest` to store the index of the largest element and set it to 0.
 

2. Iterate through the array from index 1 to n-1 and update `largest` if the current element is greater than the element at index `largest`.
 

3. Initialize another variable `secondLargest` to store the index of the second largest element and set it to -1.
 

4. Iterate through the array again from index 0 to n-1 and update `secondLargest` if the current element is smaller than the element at index `largest` and greater than the element at index
 `secondLargest`.
 

5. Return the element at index `secondLargest`.

Implementation 

  • C++
  • Java
  • Python

C++

#include <iostream>
using namespace std;

int findSecondLargest(int arr[], int n) {
int largest = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[largest])
largest = i;
}

int secondLargest = -1;
for (int i = 0; i < n; i++) {
if (arr[i] != arr[largest]) {
if (secondLargest == -1 || arr[i] > arr[secondLargest])
secondLargest = i;
}
}

if (secondLargest == -1)
return -1; // No second largest element
return arr[secondLargest];
}

int main() {
int arr[] = {10, 5, 8, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int secondLargest = findSecondLargest(arr, n);
if (secondLargest == -1)
cout << "No second largest element" << endl;
else
cout << "Second largest element: " << secondLargest << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

public class SecondLargest {
public static int findSecondLargest(int[] arr) {
int n = arr.length;
int largest = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[largest])
largest = i;
}

int secondLargest = -1;
for (int i = 0; i < n; i++) {
if (arr[i] != arr[largest]) {
if (secondLargest == -1 || arr[i] > arr[secondLargest])
secondLargest = i;
}
}

if (secondLargest == -1)
return -1; // No second largest element
return arr[secondLargest];
}

public static void main(String[] args) {
int[] arr = {10, 5, 8, 20, 15};
int secondLargest = findSecondLargest(arr);
if (secondLargest == -1)
System.out.println("No second largest element");
else
System.out.println("Second largest element: " + secondLargest);
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def findSecondLargest(arr):
n = len(arr)
largest = 0
for i in range(1, n):
if arr[i] > arr[largest]:
largest = i

secondLargest = -1
for i in range(n):
if arr[i] != arr[largest]:
if secondLargest == -1 or arr[i] > arr[secondLargest]:
secondLargest = i

if secondLargest == -1:
return -1 # No second largest element
return arr[secondLargest]

arr = [10, 5, 8, 20, 15]
secondLargest = findSecondLargest(arr)
if secondLargest == -1:
print("No second largest element")
else:
print("Second largest element:", secondLargest)
You can also try this code with Online Python Compiler
Run Code

 

Output

Second largest element: 15


Time Complexity: O(n), where n is the number of elements in the array.

Space Complexity: O(1) as we are using only a constant amount of extra space.

Approach 2 (Better Solution)

In the previous approach, we iterate through the array twice, which can be optimized. We can find the second largest element in a single traversal of the array. 


Let’s look at the step-by-step algorithm:

1. Initialize two variables, `largest` and `secondLargest`, to store the largest and second largest elements. Set `largest` to the first element (arr[0]) and `secondLargest` to a small value, like INT_MIN.
 

2. Iterate through the array starting from index 1:

  • If the current element is greater than `largest`, update `secondLargest` to `largest` and `largest` to the current element.
     
  •  If the current element is greater than `secondLargest` and not equal to `largest`, update `secondLargest` to the current element.
     

3. Return `secondLargest`.

  • C++
  • Java
  • Python

C++

#include <iostream>
#include <climits>
using namespace std;

int findSecondLargest(int arr[], int n) {
int largest = arr[0];
int secondLargest = INT_MIN;

for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

if (secondLargest == INT_MIN)
return -1; // No second largest element
return secondLargest;
}

int main() {
int arr[] = {10, 5, 8, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int secondLargest = findSecondLargest(arr, n);
if (secondLargest == -1)
cout << "No second largest element" << endl;
else
cout << "Second largest element: " << secondLargest << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

public class SecondLargest {
public static int findSecondLargest(int[] arr) {
int n = arr.length;
int largest = arr[0];
int secondLargest = Integer.MIN_VALUE;

for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

if (secondLargest == Integer.MIN_VALUE)
return -1; // No second largest element
return secondLargest;
}

public static void main(String[] args) {
int[] arr = {10, 5, 8, 20, 15};
int secondLargest = findSecondLargest(arr);
if (secondLargest == -1)
System.out.println("No second largest element");
else
System.out.println("Second largest element: " + secondLargest);
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def findSecondLargest(arr):
n = len(arr)
largest = arr[0]
secondLargest = float('-inf')

for i in range(1, n):
if arr[i] > largest:
secondLargest = largest
largest = arr[i]
elif arr[i] > secondLargest and arr[i] != largest:
secondLargest = arr[i]

if secondLargest == float('-inf'):
return -1 # No second largest element
return secondLargest

arr = [10, 5, 8, 20, 15]
secondLargest = findSecondLargest(arr)
if secondLargest == -1:
print("No second largest element")
else:
print("Second largest element:", secondLargest)
You can also try this code with Online Python Compiler
Run Code


Output

Second largest element: 15


Time Complexity: O(n), where n is the number of elements in the array.

Space Complexity: O(1) as we are using only a constant amount of extra space.


Note: This approach is more efficient than the previous one as it finds the second largest element in a single traversal of the array.

Approach 3 (Efficient Solution)

The previous approach works well, but we can further optimize it by reducing the number of comparisons. Instead of updating `secondLargest` every time we find an element greater than it, we can update it only when necessary. 


Let’s see the optimized algorithm:

1. Initialize two variables, `largest` and `secondLargest`, to the first two elements of the array.
 

2. If the first element is greater than the second element, swap them.
 

3. Iterate through the array starting from index 2:

  • If the current element is greater than `largest`, update `secondLargest` to `largest` and `largest` to the current element.
     
  •  If the current element is greater than `secondLargest` and not equal to `largest`, update `secondLargest` to the current element.
     

4. Return `secondLargest`.

  • C++
  • Java
  • Python

C++

#include <iostream>
using namespace std;

int findSecondLargest(int arr[], int n) {
if (n < 2)
return -1; // No second largest element

int largest = arr[0];
int secondLargest = arr[1];

if (largest < secondLargest)
swap(largest, secondLargest);

for (int i = 2; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

return secondLargest;
}

int main() {
int arr[] = {10, 5, 8, 20, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int secondLargest = findSecondLargest(arr, n);
if (secondLargest == -1)
cout << "No second largest element" << endl;
else
cout << "Second largest element: " << secondLargest << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

public class SecondLargest {
public static int findSecondLargest(int[] arr) {
int n = arr.length;
if (n < 2)
return -1; // No second largest element

int largest = arr[0];
int secondLargest = arr[1];

if (largest < secondLargest)
swap(arr, 0, 1);

for (int i = 2; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

return secondLargest;
}

private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

public static void main(String[] args) {
int[] arr = {10, 5, 8, 20, 15};
int secondLargest = findSecondLargest(arr);
if (secondLargest == -1)
System.out.println("No second largest element");
else
System.out.println("Second largest element: " + secondLargest);
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def findSecondLargest(arr):
n = len(arr)
if n < 2:
return -1 # No second largest element

largest = arr[0]
secondLargest = arr[1]

if largest < secondLargest:
largest, secondLargest = secondLargest, largest

for i in range(2, n):
if arr[i] > largest:
secondLargest = largest
largest = arr[i]
elif arr[i] > secondLargest and arr[i] != largest:
secondLargest = arr[i]

return secondLargest

arr = [10, 5, 8, 20, 15]
secondLargest = findSecondLargest(arr)
if secondLargest == -1:
print("No second largest element")
else:
print("Second largest element:", secondLargest)
You can also try this code with Online Python Compiler
Run Code


Output

Second largest element: 15


Time Complexity: O(n), where n is the number of elements in the array.

Space Complexity: O(1) as we are using only a constant amount of extra space.


Note: This approach is the most efficient among the three as it minimizes the number of comparisons and finds the second largest element in a single traversal of the array.

Frequently Asked Questions

What if the array contains duplicate elements?

If the array contains duplicate elements, we consider the second occurrence of the largest element as the second largest element. For example, in the array [5, 2, 8, 8, 1], the second largest element would be 8.

Can we solve this problem using sorting?

Yes, we can solve this problem by sorting the array in descending order and returning the second element. However, sorting the array would take O(n log n) time complexity, which is less efficient compared to the linear time complexity of the efficient approach discussed above.

What if the array has less than two elements?

If the array has less than two elements, there is no second largest element. In such cases, we can return a special value, like -1, to indicate that there is no second largest element in the array.

Conclusion

In this article, we learned how to find the second largest element in an array efficiently. We discussed three different approaches. We started from a simple solution and progressed to an efficient solution. The efficient approach finds the second largest element in a single traversal of the array, which minimizes the number of comparisons. 

You can also check out our other blogs on Code360.

Live masterclass