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.
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 element
Naive 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.
Below is the implementation of the above idea:
C++
// C++ program to find second largest element in an array #include <bits/stdc++.h> using namespace std; /* 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 ; } // sort the array sort(arr, arr + arr_size); // start from second last element as the largest element // is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not equal to largest element 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" ); } /* Driver program to test above function */ int main() { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof (arr) / sizeof (arr[0]); 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 <stdio.h> #include<stdlib.h> // Compare function for qsort int cmpfunc( const void * a, const void * b) { return (*( int *)a - *( int *)b); } /* 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 ; } // sort the array qsort (arr, arr_size, sizeof ( int ), cmpfunc); // start from second last element as the largest element // is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element 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" ); } /* Driver program to test above function */ int main() { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof (arr) / sizeof (arr[0]); 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( 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 ; } // Sort the array Arrays.sort(arr); // Start from second last element // as the largest element is at last for (i = arr_size - 2 ; i >= 0 ; i--) { // If the element is not // equal to largest element 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" ); } // 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 gauravrajput1 |
Python3
# Python3 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 # Sort the array arr.sort # Start from second last # element as the largest # element is at last for i in range (arr_size - 2 , - 1 , - 1 ): # If the element is not # equal to largest element if (arr[i] ! = arr[arr_size - 1 ]) : 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) { int i; // There should be // atleast two elements if (arr_size < 2) { Console.Write( " Invalid Input " ); return ; } // Sort the array Array.Sort(arr); // Start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // If the element is not // equal to largest element 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" ); } // 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
<script> // Javascript program to find second largest // element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i, first, second; // There should be atleast two elements if (arr_size < 2) { document.write( " Invalid Input " ); return ; } // sort the array arr.sort(); // start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element 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>" ); } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Surbhi Tyagi </script> |
The second largest element is 34
Complexity Analysis:
- Time Complexity: O(n log n).
The time required to sort the array is O(n log n). - Auxiliary space: O(1).
As no extra space is required.
Much More Efficient and Easy to Understand:
The Approach:
Here,we use set for avoiding duplicates and we just return the second last element as we know set store in sorted order.
C++
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { //given vector vector< int >v{12, 35, 1, 10, 34, 1}; //inserting all the element form vector v to set s. set< int >s(v.begin(),v.end()); //clear the vector. v.clear(); //insert all element back in vector in sorted order. for ( auto it:s)v.push_back(it); //the size of updated vector. int n=v.size(); //printing the second largest element in vector. cout<< "The Second Largest Element in Vector is: " ; cout<<v[n-2]<<endl; return 0; } |
Python3
# Python3 code for the above approach if __name__ = = "__main__" : # Given vector v = [ 12 , 35 , 1 , 10 , 34 , 1 ] # Print the second largest element in the vector # Converting the given vector to a set to remove duplicates s = set (v) # Sorting the set s = sorted (s) print ( "The Second Largest Element in Vector is: " ,s[ - 2 ]) #This code is contributed by nikhilsainiofficial546 |
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class Gfg { public static void Main( string [] args) { // given array int [] v = {12, 35, 1, 10, 34, 1}; // inserting all the element form vector v to set s. SortedSet< int > s = new SortedSet< int >(); for ( int i = 0; i < v.Length; i++) s.Add(v[i]); // clear the vector. List< int > ans = new List< int >(); // insert all element back in vector in sorted order. foreach ( int res in s) { ans.Add(res); } // the size of updated vector. int n = ans.Count; // printing the second largest element in vector. Console.Write( "The Second Largest Element in Vector is: " ); Console.Write(ans[n-2]); } } // This code is contributed by poojaagarwal2. |
Javascript
// given vector let v = [12, 35, 1, 10, 34, 1]; // insertig all the element from vector v to set s. let s = []; for (let i = 0; i<v.length; i++) s.push(v[i]); // clear the vector v = []; s.sort(); // insert all element back in vector in sorted order s.forEach( function (value){ v.push(value); }) // the size of updated vector let n = v.length; // pringing the second largest element in vector console.log( "The Second largest element in vector is : " + v[n-2]); // THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002) |
Java
import java.util.*; public class Main { public static void main(String[] args) { //given ArrayList List<Integer> v = new ArrayList<>(Arrays.asList( 12 , 35 , 1 , 10 , 34 , 1 )); //inserting all the elements from ArrayList v to TreeSet s. Set<Integer> s = new TreeSet<>(v); //clear the ArrayList. v.clear(); //insert all elements back in ArrayList in sorted order. for ( int value : s) { v.add(value); } //the size of updated ArrayList. int n = v.size(); //printing the second largest element in ArrayList. System.out.print( "The Second Largest Element in ArrayList is: " ); System.out.println(v.get(n- 2 )); } } |
The Second Largest Element in Vector is: 34
Complexity Analysis:
Time Complexity: O(N log N).
The Time Required To Insert Into Set And Traversing It O(N log N).
Auxiliary space: O(N).
As Required For Set.
Efficient 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.
Below is the implementation of the above idea:
C++14
// C++ program to find the second largest element in the array #include <iostream> 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[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
// 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
<script> // Javascript program to find second largest // element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write( " Invalid Input " ); return ; } // finding the largest element for (i = 0;i<arr_size;i++){ if (arr[i]>largest){ largest = arr[i]; } } // Now find the second largest element 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 ; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); </script> |
Second largest : 34
Complexity Analysis:
- Time Complexity: O(n).
Two traversals of the array are needed. - Auxiliary space: O(1).
As no extra space is required.
Efficient 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.
Below is the implementation of the above approach:
C
// C program to find second largest // element in an array #include <limits.h> #include <stdio.h> /* 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[0]); print2largest(arr, n); return 0; } |
C++
// C++ program to find the second largest element #include <iostream> 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[0])); if (index == -1) cout << "Second Largest didn't exist" ; else cout << "Second largest : " << arr[index]; } |
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. |
PHP
<?php // PHP program to find second largest // element in an array // Function to print the // second largest elements function print2largest( $arr , $arr_size ) { // There should be atleast // two elements if ( $arr_size < 2) { echo ( " Invalid Input " ); return ; } $first = $second = PHP_INT_MIN; 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 == 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. ?> |
Javascript
<script> // Javascript program to find second largest // element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write( " Invalid Input " ); return ; } // finding the largest element 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 ; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Shaswat Singh </script> |
The second largest element is 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.
Another Approach for finding the second largest using the map data structure
Step 1: Initialize a map data.
Step 2: Store the elements of the array with their count in the map and map data structure always arrange the elements in their increasing order.
Step 3: If map size is greater than 1 then second largest exist else not exist.
Step 4: If size greater 1 then get the second last key from end by using rbegin() of map data structure because every key will be distinct.
Step 5: Finally print the second largest.
Let’s see the implementation for the above algorithm : –
C++
#include <bits/stdc++.h> using namespace std; void secondLargest( int n, vector< int > vec){ // size of array should be greater than 1 if (n < 2){ cout << "Invalid Input" ; return ; } map< int , int > count; for ( int i = 0; i < n; i++){ count[vec[i]]++; } // Checking if count size is equal to 1 it // means only largest element exist there is no second // largest element if (count.size() == 1){ cout << "No Second largest element exist" ; return ; } int size = 1; for ( auto it = count.rbegin(); it != count.rend(); it++){ if (size == 2){ cout << "The second largest element is: " << it->first; break ; } size++; } cout << endl; } int main() { vector< int > vec = { 12, 35, 1, 10, 34, 1 }; secondLargest(vec.size(), vec); return 0; } |
Java
import java.util.*; public class Main { public static void main(String[] args) { int [] vec = { 12 , 35 , 1 , 34 , 10 , 1 }; secondLargest(vec.length, vec); } public static void secondLargest( int n, int [] vec) { // size of array should be greater than 1 if (n < 2 ) { System.out.println( "Invalid Input" ); return ; } TreeMap<Integer, Integer> count = new TreeMap<>(Collections.reverseOrder()); for ( int i = 0 ; i < n; i++) { count.put(vec[i], count.getOrDefault(vec[i], 0 ) + 1 ); } // Checking if count size is equal to 1 it // means only largest element exist there is no // second largest element if (count.size() == 1 ) { System.out.println( "No Second largest element exist" ); return ; } int size = 1 ; for (Map.Entry<Integer, Integer> it : count.entrySet()) { if (size == 2 ) { System.out.println( "The second largest element is: " + it.getKey()); break ; } size++; } System.out.println(); } } // This code is contributed by Tapesh(tapeshdua420) |
Python3
from collections import defaultdict def second_largest(n, vec): # size of array should be greater than 1 if n < 2 : print ( "Invalid Input" ) return count = defaultdict( int ) for i in range (n): count[vec[i]] + = 1 # Checking if count size is equal to 1 it # means only largest element exist there is no second # largest element if len (count) = = 1 : print ( "No Second largest element exist" ) return # sort the dictionary by key in descending order count_sorted = sorted (count.items(), key = lambda x: x[ 0 ], reverse = True ) second_largest = None for i, (key, value) in enumerate (count_sorted): if i = = 1 : second_largest = key break if second_largest is not None : print ( "The second largest element is:" , second_largest) vec = [ 12 , 35 , 1 , 10 , 34 , 1 ] second_largest( len (vec), vec) # This code is contributed by divyansh2212 |
Javascript
function secondLargest(n, vec){ // size of array should be greater than 1 if (n < 2){ console.log( "Invalid Input" ); return ; } let count = {}; for (let i = 0; i < n; i++){ if (vec[i] in count){ count[vec[i]] += 1; } else { count[vec[i]] = 1; } } // checking if count size is equal to 1 // it means only largest element exist // there is no second largest element if (count.length == 1){ console.log( "No second largest element exist" ); return ; } let keys = Object.keys(count); console.log(keys[keys.length-2]); } let vec = [12, 35, 1, 10, 34, 1]; secondLargest(vec.length, vec); // This code is contributed by sdeadityasharma. |
C#
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); } } |
The second largest element is: 34
Time Complexity: O(n), where n = size of array
Auxiliary Space: O(n)
Another Approach for finding the second largest element using the priority queue data structure
In C++ priority queue by default behaves like a max-heap. So in the priority queue, top element is the largest among all the elements that are present in that priority queue.
So here we will push all elements into a priority queue. Now its top element will be the largest element, so we will pop the top element. Now the element present at the top is the second largest element. So we will simply print that.
Code-
C++
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { //Given vector vector< int >v{12, 35, 1, 10, 34, 1}; //Made a priority queue priority_queue< int > pq; //inserting all the element form vector v to priority queue pq. for ( int i=0;i<v.size();i++){ pq.push(v[i]); } //Remove largest element from pq pq.pop(); //Now top of priority queue is second largest element cout<< "The Second Largest Element in Vector is: " ; cout<<pq.top()<<endl; return 0; } |
The Second Largest Element in Vector is: 34
Time Complexity: O(nlogn)
Auxiliary Space: O(n), for priority queue
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 Login to comment...