Tutorialspoint
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.
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.
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)
ArraysGoldman SachsAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize two variables 'largest' and 'secondLargest' to negative infinity
 Step 2: Iterate through each element in the array using a for loop
 Step 3: For each element, first check if it's greater than the current largest element
 Step 4: If yes, update secondLargest to the previous largest value and set largest to current element
 Step 5: If no, check if the element is greater than secondLargest but less than largest
 Step 6: If this condition is true, update secondLargest to the current element
 Step 7: After the loop, check if secondLargest is still negative infinity and return -1 if true, otherwise return secondLargest

Submitted Code :