DSA problem
Find the Second Largest Element
Given an array of N integers, find the second largest distinct element. If no such element exists, return -1.
A naive approach sorts the array and picks the second-to-last unique element in O(N log N). But you can do it in a single pass with O(N) time. Track two variables: first (largest) and second (second largest). For each element: if it is greater than first, shift first down into second and update first. If it is strictly between second and first, update second.
The key subtlety is handling duplicates - if the array is [5, 5, 5], there is no second largest, so the answer is -1. This problem teaches you to maintain multiple running states simultaneously.
Examples
nums = [12, 35, 1, 10, 34, 1]34Constraints
- 2 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.