Tutorialspoint
Problem
Solution
Submissions

Second Largest Element in an Array

Certification: Basic Level Accuracy: 42.86% Submissions: 7 Points: 10

Write a C++ function to find the second largest element in an array of integers.

Example 1
  • Input: array = [5, 3, 8, 1]
  • Output: 5
  • Explanation:
    • Step 1: Find the largest element in the array (8).
    • Step 2: Find the second largest element (5).
    • Step 3: Return the second largest element.
Example 2
  • Input: array = [10, 2, 7, 4]
  • Output: 7
  • Explanation:
    • Step 1: Find the largest element in the array (10).
    • Step 2: Find the second largest element (7).
    • Step 3: Return the second largest element.
Constraints
  • 2 ≤ array length ≤ 10^4
  • -10^5 ≤ array elements ≤ 10^5
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysNumberControl StructuresFacebookEY
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

  • Traverse the array and keep track of the largest and second-largest elements.
  • Handle edge cases where all elements are the same.
  • Ensure the function works for the upper limit of the constraint.

Steps to solve by this approach:

 Step 1: Define a function second_largest that takes a vector of integers.
 Step 2: Initialize two variables to track the largest and second largest values.
 Step 3: Iterate through the array checking each element.
 Step 4: If the current element is larger than the largest, update both largest and second largest.
 Step 5: If the current element is between largest and second largest, update second largest.
 Step 6: Return the second largest value.
 Step 7: In main, call second_largest with a vector and print the result.

Submitted Code :