# Find Second largest element in an array

Given an array of integers, our task is to write a program that efficiently finds the second-largest element present in the array.

Examples:

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 element

Recommended Practice

## Find Second Largest element using Sorting:

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.

Below is the implementation of the above idea:

## C++

 `// C++ program to find second largest element in an array`   `#include ` `using` `namespace` `std;`   `/* Function to print the second largest elements */` `void` `print2largest(``int` `arr[], ``int` `arr_size)` `{` `    ``// sort the array in descending order` `    ``sort(arr, arr + arr_size, greater<``int``>());` `    ``// start from second element as first` `    ``// element is the largest` `    ``for` `(``int` `i = 1; i < arr_size; i++) {` `        ``// if the element is not equal to largest element` `        ``if` `(arr[i] != arr) {` `            ``printf``(``"The second largest element is %d\n"``,` `                   ``arr[i]);` `            ``return``;` `        ``}` `    ``}` `    ``printf``(``"There is no second largest element\n"``);` `}`   `/* Driver program to test above function */` `int` `main()` `{` `    ``int` `arr[] = { 12, 35, 1, 10, 34, 1 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``print2largest(arr, n);` `    ``return` `0;` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## C

 `// C program to find second largest element in an array` `#include ` `#include `   `// Compare function for qsort` `int` `cmpfunc(``const` `void``* a, ``const` `void``* b)` `{` `    ``return` `(*(``int``*)b - *(``int``*)a);` `}`   `/* Function to print the second largest elements */` `void` `print2largest(``int` `arr[], ``int` `arr_size)` `{` `    ``// sort the array in descending order` `    ``qsort``(arr, arr_size, ``sizeof``(``int``), cmpfunc);` `    ``// start from second element as first` `    ``// element is the largest` `    ``for` `(``int` `i = 1; i < arr_size; i++) {` `        ``// if the element is not equal` `        ``// to the largest element` `        ``if` `(arr[i] != arr) {` `            ``printf``(``"The second largest element is %d\n"``,` `                   ``arr[i]);` `            ``return``;` `        ``}` `    ``}` `    ``printf``(``"There is no second largest element\n"``);` `}`   `/* Driver program to test above function */` `int` `main()` `{` `    ``int` `arr[] = { 12, 35, 1, 10, 34, 1 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``print2largest(arr, n);` `    ``return` `0;` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `// Java program to find second largest` `// element in an array` `import` `java.util.*;` `class` `GFG {`   `    ``// Function to print the` `    ``// second largest elements` `    ``static` `void` `print2largest(Integer arr[], ``int` `arr_size)` `    ``{` `        ``// Sort the array in descending order` `        ``Arrays.sort(arr, Collections.reverseOrder());` `        ``// Start from second element as first` `        ``// element is the largest` `        ``for` `(``int` `i = ``1``; i < arr_size; i++) {` `            ``// If the element is not` `            ``// equal to largest element` `            ``if` `(arr[i] != arr[``0``]) {` `                ``System.out.printf(``"The second largest "` `                                      ``+ ``"element is %d\n"``,` `                                  ``arr[i]);` `                ``return``;` `            ``}` `        ``}`   `        ``System.out.printf(``"There is no second "` `                          ``+ ``"largest element\n"``);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``Integer arr[] = { ``12``, ``35``, ``1``, ``10``, ``34``, ``1` `};` `        ``int` `n = arr.length;` `        ``print2largest(arr, n);` `    ``}` `}`   `// This code is contributed by gauravrajput1`

## Python3

 `# Python3 program to find second` `# largest element in an array`   `# Function to print the` `# second largest elements`     `def` `print2largest(arr, arr_size):`   `    ``# Sort the array in descending order` `    ``arr.sort(reverse``=``True``)`   `    ``# Start from second last element as first` `    ``# element is the largest` `    ``for` `i ``in` `range``(``1``, arr_size):`   `        ``# If the element is not` `        ``# equal to largest element` `        ``if` `(arr[i] !``=` `arr[``0``]):` `            ``print``(``"The second largest element is"``, arr[i])` `            ``return`   `    ``print``(``"There is no second largest element"``)`     `# Driver code` `arr ``=` `[``12``, ``35``, ``1``, ``10``, ``34``, ``1``]` `n ``=` `len``(arr)` `print2largest(arr, n)`   `# This code is contributed by divyeshrabadiya07`

## C#

 `// C# program to find second largest` `// element in an array` `using` `System;`   `class` `GFG{`   `// Function to print the ` `// second largest elements` `static` `void` `print2largest(``int` `[]arr, ` `                          ``int` `arr_size)` `{` `  ``// Sort the array in descending order` `  ``Array.Sort(arr);` `  ``Array.Reverse(arr);` `  ``// Start from second last element as first` `  ``// element is the largest element` `  ``for``(``int` `i = 1; i < arr_size; i--) ` `  ``{` `    ``// If the element is not` `    ``// equal to largest element` `    ``if` `(arr[i] != arr) ` `    ``{` `      ``Console.Write(``"The second largest "` `+ ` `                    ``"element is {0}\n"``, arr[i]);` `      ``return``;` `    ``}` `  ``}`   `  ``Console.Write(``"There is no second "` `+` `                ``"largest element\n"``);` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `  ``int` `[]arr = { 12, 35, 1, 10, 34, 1 };` `  ``int` `n = arr.Length;` `  `  `  ``print2largest(arr, n);` `}` `}`   `// This code is contributed by Amit Katiyar`

## Javascript

 ``

Output

```The second largest element is 34
```

Time Complexity: O(nlogn), where n is the size of input array.
Auxiliary space: O(1), as no extra space is required.

## Find Second Largest element by traversing the array twice (Two Pass):

The approach is to traverse the array twice. In the first traversal, find the maximum element. In the second traversal, find the greatest element excluding the previous greatest.

Below is the implementation of the above idea:

## C++14

 `// C++ program to find the second largest element in the array` `#include ` `using` `namespace` `std;`     `int` `secondLargest(``int` `arr[], ``int` `n) {` `    ``int` `largest = 0, secondLargest = -1;`   `    ``// finding the largest element in the array` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``if` `(arr[i] > arr[largest])` `            ``largest = i;` `    ``}`   `    ``// finding the largest element in the array excluding ` `    ``// the largest element calculated above` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(arr[i] != arr[largest]) {` `            ``// first change the value of second largest ` `            ``// as soon as the next element is found` `            ``if` `(secondLargest == -1)` `                ``secondLargest = i;` `            ``else` `if` `(arr[i] > arr[secondLargest])` `                ``secondLargest = i;` `        ``}` `    ``}` `    ``return` `secondLargest;` `}`     `int` `main() {` `    ``int` `arr[] = { 12, 35, 1, 10, 34, 1 };` `    ``int` `n = ``sizeof``(arr)/``sizeof``(arr);` `    ``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

 `// Java program to find second largest` `// element in an array` `import` `java.io.*;`   `class` `GFG{`   `// Function to print the second largest elements ` `static` `void` `print2largest(``int` `arr[], ``int` `arr_size)` `{` `    ``int` `i, first, second;`   `    ``// There should be atleast two elements` `    ``if` `(arr_size < ``2``)` `    ``{` `        ``System.out.printf(``" Invalid Input "``);` `        ``return``;` `    ``}`   `    ``int` `largest = second = Integer.MIN_VALUE;`   `    ``// Find the largest element` `    ``for``(i = ``0``; i < arr_size; i++)` `    ``{` `        ``largest = Math.max(largest, arr[i]);` `    ``}`   `    ``// Find the second largest element` `    ``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);` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `arr[] = { ``12``, ``35``, ``1``, ``10``, ``34``, ``1` `};` `    ``int` `n = arr.length;` `    `  `    ``print2largest(arr, n);` `}` `}`   `// This code is contributed by Amit Katiyar`

## Python3

 `# Python3 program to find ` `# second largest element ` `# in an array`   `# Function to print ` `# second largest elements` `def` `print2largest(arr, arr_size):`   `    ``# There should be atleast ` `    ``# two elements` `    ``if` `(arr_size < ``2``):` `        ``print``(``" Invalid Input "``);` `        ``return``;`   `    ``largest ``=` `second ``=` `-``2454635434``;`   `    ``# Find the largest element` `    ``for` `i ``in` `range``(``0``, arr_size):` `        ``largest ``=` `max``(largest, arr[i]);`   `    ``# Find the second largest element` `    ``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);`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `  `  `    ``arr ``=` `[``12``, ``35``, ``1``, ` `           ``10``, ``34``, ``1``];` `    ``n ``=` `len``(arr);` `    ``print2largest(arr, n);`   `# This code is contributed by shikhasingrajput`

## C#

 `// C# program to find second largest` `// element in an array` `using` `System;`   `class` `GFG{`   `// Function to print the second largest elements ` `static` `void` `print2largest(``int` `[]arr, ``int` `arr_size)` `{` `    ``// int first;` `    ``int` `i, second;`   `    ``// There should be atleast two elements` `    ``if` `(arr_size < 2)` `    ``{` `        ``Console.Write(``" Invalid Input "``);` `        ``return``;` `    ``}`   `    ``int` `largest = second = ``int``.MinValue;`   `    ``// Find the largest element` `    ``for``(i = 0; i < arr_size; i++)` `    ``{` `        ``largest = Math.Max(largest, arr[i]);` `    ``}`   `    ``// Find the second largest element` `    ``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);` `}`   `// Driver code` `public` `static` `void` `Main(String[] args)` `{` `    ``int` `[]arr = { 12, 35, 1, 10, 34, 1 };` `    ``int` `n = arr.Length;` `    `  `    ``print2largest(arr, n);` `}` `} `   `// This code is contributed by Amit Katiyar`

## Javascript

 ``

Output

`Second largest : 34`

Time Complexity: O(n), where n is the size of input array.
Auxiliary space: O(1), as no extra space is required.

## Find Second Largest element by traversing the array once (One Pass):

The idea is to keep track of the largest and second largest element while traversing the array. If an element is greater than the largest element, we update the largest as well as the second largest. Else if an element is smaller than largest but greater than second largest, then we update the second largest only.

Below is the complete algorithm for doing this:

• Initialize the first as 0(i.e, index of arr element
• Start traversing the array from array,
• If the current element in array say arr[i] is greater than first. Then update first and second as, second = first and first = arr[i]
• If the current element is in between first and second, then update second to store the value of current variable as second = arr[i]
• Return the value stored in second.

Below is the implementation of the above approach:

## C++

 `// C++ program to find the second largest element`   `#include ` `using` `namespace` `std;`   `// returns the index of second largest` `// if second largest didn't exist return -1` `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[] = { 12, 35, 1, 10, 34, 1 };` `    ``int` `index = secondLargest(arr, ``sizeof``(arr)/``sizeof``(arr));` `    ``if` `(index == -1)` `        ``cout << ``"Second Largest didn't exist"``;` `    ``else` `        ``cout << ``"Second largest : "` `<< arr[index];` `}`

## C

 `// C program to find second largest` `// element in an array`   `#include ` `#include `   `/* Function to print the second largest elements */` `void` `print2largest(``int` `arr[], ``int` `arr_size)` `{` `    ``int` `i, first, second;`   `    ``/* There should be atleast two elements */` `    ``if` `(arr_size < 2) {` `        ``printf``(``" Invalid Input "``);` `        ``return``;` `    ``}`   `    ``first = second = INT_MIN;` `    ``for` `(i = 0; i < arr_size; i++) {` `        ``/* If current element is greater than first` `           ``then update both first and second */` `        ``if` `(arr[i] > first) {` `            ``second = first;` `            ``first = arr[i];` `        ``}`   `        ``/* If arr[i] is in between first and ` `           ``second then update second  */` `        ``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);` `}`   `/* Driver program to test above function */` `int` `main()` `{` `    ``int` `arr[] = { 12, 35, 1, 10, 34, 1 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``print2largest(arr, n);` `    ``return` `0;` `}`

## Java

 `// JAVA Code for Find Second largest` `// element in an array` `import` `java.io.*;`   `class` `GFG {`   `    ``/* Function to print the second largest` `    ``elements */` `    ``public` `static` `void` `print2largest(``int` `arr[],` `                                     ``int` `arr_size)` `    ``{` `        ``int` `i, first, second;`   `        ``/* There should be atleast two elements */` `        ``if` `(arr_size < ``2``) {` `            ``System.out.print(``" Invalid Input "``);` `            ``return``;` `        ``}`   `        ``first = second = Integer.MIN_VALUE;` `        ``for` `(i = ``0``; i < arr_size; i++) {` `            ``/* If current element is greater than ` `            ``first then update both first and second */` `            ``if` `(arr[i] > first) {` `                ``second = first;` `                ``first = arr[i];` `            ``}`   `            ``/* If arr[i] is in between first and ` `               ``second then update second  */` `            ``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);` `    ``}`   `    ``/* Driver program to test above function */` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { ``12``, ``35``, ``1``, ``10``, ``34``, ``1` `};` `        ``int` `n = arr.length;` `        ``print2largest(arr, n);` `    ``}` `}` `// This code is contributed by Arnav Kr. Mandal.`

## Python3

 `# Python program to` `# find second largest ` `# element in an array`     `# Function to print the` `# second largest elements ` `def` `print2largest(arr, arr_size):`   `    ``# There should be atleast` `        ``# two elements ` `    ``if` `(arr_size < ``2``):` `    `  `        ``print``(``" Invalid Input "``)` `        ``return` `    `    `    ``first ``=` `second ``=` `-``2147483648` `    ``for` `i ``in` `range``(arr_size):` `    `  `        ``# If current element is` `                ``# smaller than first` `        ``# then update both` `                ``# first and second ` `        ``if` `(arr[i] > first):` `        `  `            ``second ``=` `first` `            ``first ``=` `arr[i]` `        `    `        ``# If arr[i] is in` `                ``# between first and ` `        ``# second then update second ` `        ``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)`     `# Driver program to test` `# above function ` `arr ``=` `[``12``, ``35``, ``1``, ``10``, ``34``, ``1``]` `n ``=` `len``(arr)`   `print2largest(arr, n)`   `# This code is contributed` `# by Anant Agarwal.`

## C#

 `// C# Code for Find Second largest` `// element in an array` `using` `System;`   `class` `GFG {`   `    ``// Function to print the` `    ``// second largest elements` `    ``public` `static` `void` `print2largest(``int``[] arr,` `                                     ``int` `arr_size)` `    ``{` `        ``int` `i, first, second;`   `        ``// There should be atleast two elements` `        ``if` `(arr_size < 2) {` `            ``Console.WriteLine(``" Invalid Input "``);` `            ``return``;` `        ``}`   `        ``first = second = ``int``.MinValue;` `        ``for` `(i = 0; i < arr_size; i++) {` `            ``// If current element is smaller than` `            ``// first then update both first and second` `            ``if` `(arr[i] > first) {` `                ``second = first;` `                ``first = arr[i];` `            ``}`   `            ``// If arr[i] is in between first` `            ``// and second then update second` `            ``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);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(String[] args)` `    ``{` `        ``int``[] arr = { 12, 35, 1, 10, 34, 1 };` `        ``int` `n = arr.Length;` `        ``print2largest(arr, n);` `    ``}` `}`   `// This code is contributed by Parashar.`

## Javascript

 ``

## PHP

 ` ``\$first``)` `        ``{` `            ``\$second` `= ``\$first``;` `            ``\$first` `= ``\$arr``[``\$i``];` `        ``}`   `        ``// If arr[i] is in ` `        ``// between first and ` `        ``// second then update ` `        ``// second ` `        ``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"``);` `}`   `// Driver Code` `\$arr` `= ``array``(12, 35, 1, 10, 34, 1);` `\$n` `= sizeof(``\$arr``);` `print2largest(``\$arr``, ``\$n``);`   `// This code is contributed by Ajit.` `?>`

Output

`Second largest : 34`

Time Complexity: O(n), where n is the size of input array.
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.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next