Second Largest Element - Problem

Given an array of integers, find the second largest element without sorting the array. The array may contain duplicates.

You need to handle edge cases where:

  • All elements are the same
  • Array has only two elements
  • Multiple elements have the same maximum value

Return the second largest distinct value. If no second largest element exists, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3, 1, 4, 1, 5, 9, 2]
Output: 5
💡 Note: The largest element is 9, and the second largest distinct element is 5
Example 2 — With Duplicates
$ Input: nums = [2, 2, 1, 3]
Output: 2
💡 Note: The largest element is 3, and the second largest distinct element is 2
Example 3 — All Same Elements
$ Input: nums = [1, 1, 1, 1]
Output: -1
💡 Note: All elements are the same, so no second largest distinct element exists

Constraints

  • 2 ≤ nums.length ≤ 104
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
INPUT ARRAYALGORITHMRESULT3141592Find second largestdistinct element1Initialize Variablesfirst = -∞, second = -∞2Process Each ElementUpdate first & second smartly3Track Maximum Valuesfirst = 9, second = 54Return SecondOutput: 55Second LargestThe largest element is 9The second largest is 5ComplexityTime: O(n)Space: O(1)Key Insight:Track only the two largest values in a single pass - no need to sort the entire array!This reduces time complexity from O(n log n) to O(n) while using constant space.TutorialsPoint - Second Largest Element | Single Pass Algorithm
Asked in
Amazon 45 Google 38 Microsoft 32 Apple 28
35.0K Views
High Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen