Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.
Example:
Input: arr[] = {12, 35, 1, 10, 34, 1}
Output: The second largest element is 34.
Explanation: The largest element of the
array is 35 and the second
largest element is 34
Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of
the array is 10 and the second
largest element is 5
Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array
is 10 there is no second largest elementSimple Solution
Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array.
C++14
#include <bits/stdc++.h>
using namespace std;
void print2largest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2) {
printf(" Invalid Input ");
return;
}
sort(arr, arr + arr_size);
for (i = arr_size - 2; i >= 0; i--) {
if (arr[i] != arr[arr_size - 1]) {
printf("The second largest element is %d\n", arr[i]);
return;
}
}
printf("There is no second largest element\n");
}
int main()
{
int arr[] = { 12, 35, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print2largest(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
if (arr_size < 2)
{
System.out.printf(" Invalid Input ");
return;
}
Arrays.sort(arr);
for (i = arr_size - 2; i >= 0; i--)
{
if (arr[i] != arr[arr_size - 1])
{
System.out.printf("The second largest " +
"element is %d\n", arr[i]);
return;
}
}
System.out.printf("There is no second " +
"largest element\n");
}
public static void main(String[] args)
{
int arr[] = {12, 35, 1, 10, 34, 1};
int n = arr.length;
print2largest(arr, n);
}
}
|
Python3
def print2largest(arr,
arr_size):
if (arr_size < 2):
print(" Invalid Input ")
return
arr.sort
for i in range(arr_size-2,
-1, -1):
if (arr[i] != arr[arr_size - 1]) :
print("The second largest element is",
arr[i])
return
print("There is no second largest element")
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
|
C#
using System;
class GFG{
static void print2largest(int []arr,
int arr_size)
{
int i;
if (arr_size < 2)
{
Console.Write(" Invalid Input ");
return;
}
Array.Sort(arr);
for(i = arr_size - 2; i >= 0; i--)
{
if (arr[i] != arr[arr_size - 1])
{
Console.Write("The second largest " +
"element is {0}\n", arr[i]);
return;
}
}
Console.Write("There is no second " +
"largest element\n");
}
public static void Main(String[] args)
{
int []arr = { 12, 35, 1, 10, 34, 1 };
int n = arr.Length;
print2largest(arr, n);
}
}
|
Javascript
<script>
function print2largest(arr, arr_size) {
let i, first, second;
if (arr_size < 2) {
document.write(" Invalid Input ");
return;
}
arr.sort();
for (i = arr_size - 2; i >= 0; i--) {
if (arr[i] != arr[arr_size - 1]) {
document.write("The second largest element is " + arr[i]);
return;
}
}
document.write("There is no second largest element<br>");
}
let arr= [ 12, 35, 1, 10, 34, 1 ];
let n = arr.length;
print2largest(arr, n);
</script>
|
OutputThe second largest element is 34
Complexity Analysis:
- Time Complexity: O(n log n).
Time required to sort the array is O(n log n). - Auxiliary space: O(1).
As no extra space is required.
Better Solution:
Approach: The approach is to traverse the array twice.
In the first traversal find the maximum element.
In the second traversal find the greatest element in the remaining excluding the previous greatest.
C++14
#include <iostream>
using namespace std;
int secondLargest(int arr[], int n) {
int largest = 0, secondLargest = -1;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[largest])
largest = i;
}
for (int i = 0; i < n; i++) {
if (arr[i] != arr[largest]) {
if (secondLargest == -1)
secondLargest = i;
else if (arr[i] > arr[secondLargest])
secondLargest = i;
}
}
return secondLargest;
}
int main() {
int arr[] = {10, 12, 20, 4};
int n = sizeof(arr)/sizeof(arr[0]);
int second_Largest = secondLargest(arr, n);
if (second_Largest == -1)
cout << "Second largest didn't exit\n";
else
cout << "Second largest : " << arr[second_Largest];
}
|
Java
class GFG{
static void print2largest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2)
{
System.out.printf(" Invalid Input ");
return;
}
int largest = second = Integer.MIN_VALUE;
for(i = 0; i < arr_size; i++)
{
largest = Math.max(largest, arr[i]);
}
for(i = 0; i < arr_size; i++)
{
if (arr[i] != largest)
second = Math.max(second, arr[i]);
}
if (second == Integer.MIN_VALUE)
System.out.printf("There is no second " +
"largest element\n");
else
System.out.printf("The second largest " +
"element is %d\n", second);
}
public static void main(String[] args)
{
int arr[] = { 12, 35, 1, 10, 34, 1 };
int n = arr.length;
print2largest(arr, n);
}
}
|
Python3
def print2largest(arr, arr_size):
if (arr_size < 2):
print(" Invalid Input ");
return;
largest = second = -2454635434;
for i in range(0, arr_size):
largest = max(largest, arr[i]);
for i in range(0, arr_size):
if (arr[i] != largest):
second = max(second, arr[i]);
if (second == -2454635434):
print("There is no second " +
"largest element");
else:
print("The second largest " +
"element is \n", second);
if __name__ == '__main__':
arr = [12, 35, 1,
10, 34, 1];
n = len(arr);
print2largest(arr, n);
|
C#
using System;
class GFG{
static void print2largest(int []arr, int arr_size)
{
int i, second;
if (arr_size < 2)
{
Console.Write(" Invalid Input ");
return;
}
int largest = second = int.MinValue;
for(i = 0; i < arr_size; i++)
{
largest = Math.Max(largest, arr[i]);
}
for(i = 0; i < arr_size; i++)
{
if (arr[i] != largest)
second = Math.Max(second, arr[i]);
}
if (second == int.MinValue)
Console.Write("There is no second " +
"largest element\n");
else
Console.Write("The second largest " +
"element is {0}\n", second);
}
public static void Main(String[] args)
{
int []arr = { 12, 35, 1, 10, 34, 1 };
int n = arr.Length;
print2largest(arr, n);
}
}
|
Javascript
<script>
function print2largest(arr, arr_size) {
let i;
let largest = second = -2454635434;
if (arr_size < 2) {
document.write(" Invalid Input ");
return;
}
for (i = 0;i<arr_size;i++){
if (arr[i]>largest){
largest = arr[i];
}
}
for (i = 0 ;i<arr_size;i++){
if (arr[i]>second && arr[i]<largest){
second = arr[i];
}
}
if (second == -2454635434){
document.write("There is no second largest element<br>");
}
else{
document.write("The second largest element is " + second);
return;
}
}
let arr= [ 12, 35, 1, 10, 34, 1 ];
let n = arr.length;
print2largest(arr, n);
</script>
|
OutputSecond largest : 12
Complexity Analysis:
- Time Complexity: O(n).
Two traversals of the array is needed. - Auxiliary space: O(1).
As no extra space is required.
Efficient Solution
Approach: Find the second largest element in a single traversal.
Below is the complete algorithm for doing this:
1) Initialize the first as 0(i.e, index of arr[0] element
2) Start traversing the array from array[1],
a) If the current element in array say arr[i] is greater
than first. Then update first and second as,
second = first
first = arr[i]
b) If the current element is in between first and second,
then update second to store the value of current variable as
second = arr[i]
3) Return the value stored in second.C
#include <limits.h>
#include <stdio.h>
void print2largest(int arr[], int arr_size)
{
int i, first, second;
if (arr_size < 2) {
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest element\n");
else
printf("The second largest element is %d", second);
}
int main()
{
int arr[] = { 12, 35, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print2largest(arr, n);
return 0;
}
|
C++
#include <iostream>
using namespace std;
int secondLargest(int arr[], int n) {
int first = 0, second = -1;
for (int i = 1; i < n; i++) {
if (arr[i] > arr[first]) {
second = first;
first = i;
}
else if (arr[i] < arr[first]) {
if (second == -1 || arr[second] < arr[i])
second = i;
}
}
return second;
}
int main() {
int arr[] = {10, 12, 20, 4};
int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0]));
if (index == -1)
cout << "Second Largest didn't exist";
else
cout << "Second largest : " << arr[index];
}
|
Java
class GFG {
public static void print2largest(int arr[],
int arr_size)
{
int i, first, second;
if (arr_size < 2) {
System.out.print(" Invalid Input ");
return;
}
first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == Integer.MIN_VALUE)
System.out.print("There is no second largest"
+ " element\n");
else
System.out.print("The second largest element"
+ " is " + second);
}
public static void main(String[] args)
{
int arr[] = { 12, 35, 1, 10, 34, 1 };
int n = arr.length;
print2largest(arr, n);
}
}
|
Python3
def print2largest(arr, arr_size):
if (arr_size < 2):
print(" Invalid Input ")
return
first = second = -2147483648
for i in range(arr_size):
if (arr[i] > first):
second = first
first = arr[i]
elif (arr[i] > second and arr[i] != first):
second = arr[i]
if (second == -2147483648):
print("There is no second largest element")
else:
print("The second largest element is", second)
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
|
C#
using System;
class GFG {
public static void print2largest(int[] arr,
int arr_size)
{
int i, first, second;
if (arr_size < 2) {
Console.WriteLine(" Invalid Input ");
return;
}
first = second = int.MinValue;
for (i = 0; i < arr_size; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == int.MinValue)
Console.Write("There is no second largest"
+ " element\n");
else
Console.Write("The second largest element"
+ " is " + second);
}
public static void Main(String[] args)
{
int[] arr = { 12, 35, 1, 10, 34, 1 };
int n = arr.Length;
print2largest(arr, n);
}
}
|
PHP
<?php
function print2largest($arr, $arr_size)
{
if ($arr_size < 2)
{
echo(" Invalid Input ");
return;
}
$first = $second = PHP_INT_MIN;
for ($i = 0; $i < $arr_size ; $i++)
{
if ($arr[$i] > $first)
{
$second = $first;
$first = $arr[$i];
}
else if ($arr[$i] > $second &&
$arr[$i] != $first)
$second = $arr[$i];
}
if ($second == PHP_INT_MIN)
echo("There is no second largest element\n");
else
echo("The second largest element is " . $second . "\n");
}
$arr = array(12, 35, 1, 10, 34, 1);
$n = sizeof($arr);
print2largest($arr, $n);
?>
|
Javascript
<script>
function print2largest(arr, arr_size) {
let i;
let largest = second = -2454635434;
if (arr_size < 2) {
document.write(" Invalid Input ");
return;
}
for (i = 0 ;i<arr_size;i++){
if (arr[i]>largest){
second = largest ;
largest = arr[i]
}
else if (arr[i]!=largest && arr[i]>second ){
second = arr[i];
}
}
if (second == -2454635434){
document.write("There is no second largest element<br>");
}
else{
document.write("The second largest element is " + second);
return;
}
}
let arr= [ 12, 35, 1, 10, 34, 1 ];
let n = arr.length;
print2largest(arr, n);
</script>
|
Output:
Second largest : 34
Complexity Analysis:
- Time Complexity: O(n).
Only one traversal of the array is needed. - Auxiliary space: O(1).
As no extra space is required.
Related Article:
Smallest and second smallest element in an array
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.