Given an array of distinct integers, find the second largest value in a single pass, without sorting.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array of distinct integers, find the second largest value in a single pass, without sorting.
A direct extension of tracking one running maximum — this forces you to track two running values at once, the same shape you'll reuse for running-minimum and Kadane's-style problems.
Whenever a problem asks for the Nth best value with N small and fixed, think about tracking N running candidates in one pass instead of sorting the whole array.
Track two running values, largest and secondLargest, both starting below any possible input value. Scan the array once: if the current value beats largest, the old largest becomes the new secondLargest before largest is updated; otherwise, if it beats only secondLargest, update just that. One pass, two comparisons per element.
class Solution {
public int secondLargest(int[] nums) {
long largest = Long.MIN_VALUE, secondLargest = Long.MIN_VALUE;
for (int num : nums) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest) {
secondLargest = num;
}
}
return (int) secondLargest;
}
}