
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Second Largest Element in Array
								Certification: Basic Level
								Accuracy: 0%
								Submissions: 0
								Points: 5
							
							Write a JavaScript program to find the second largest element in an array of integers. If there is no second largest element (e.g., all elements are the same), return -1. The array contains at least one element.
Example 1
- Input: arr = [3, 1, 4, 1, 5, 9, 2]
 - Output: 5
 - Explanation: 
- The array contains elements [3, 1, 4, 1, 5, 9, 2]. 
 - The largest element in the array is 9. 
 - The second largest element in the array is 5. 
 - Therefore, the output is 5.
 
 - The array contains elements [3, 1, 4, 1, 5, 9, 2]. 
 
Example 2
- Input: arr = [5, 5, 5, 5]
 - Output: -1
 - Explanation: 
- The array contains elements [5, 5, 5, 5]. 
 - All elements in the array are the same (5). 
 - There is no second largest element since all values are identical. 
 - Therefore, the output is -1.
 
 - The array contains elements [5, 5, 5, 5]. 
 
Constraints
- 1 ≤ arr.length ≤ 1000
 - -1000 ≤ arr[i] ≤ 1000
 - If no second largest exists, return -1
 - Time Complexity: O(n) where n is the length of the array
 - Space Complexity: O(1)
 
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Initialize two variables to track the largest and second largest elements
 - Set both variables to negative infinity initially
 - Iterate through the array once
 - For each element, compare it with the current largest element
 - If the element is larger than the largest, update both largest and second largest
 - If the element is between largest and second largest, update only second largest
 - Make sure to handle duplicate values correctly by checking for strict inequality