Finding the Second Max
Finding the Second Max
Learn an efficient O(n) algorithm to find the second largest element in an array using a single pass and two variables, avoiding costly sorting.
Finding the second largest element in an array is a common task. While sorting the array and picking the second-to-last element works, it's often an inefficient approach, especially for large datasets. A more optimal method involves a single pass through the array, achieving O(n) time complexity.
The Inefficiency of Sorting
Sorting an array typically has a time complexity of O(n log n), which can be computationally expensive for arrays with millions of items. To find just the second largest element, performing a full sort is overkill. We can achieve the same result with significantly less work by processing the array just once.
The One-Pass Approach
The efficient method requires tracking only two values as we iterate through the array: the largest element found so far (`max`) and the second largest element found so far (`secondMax`). Both variables are initialized to a very small number (e.g., negative infinity) or the first two distinct elements of the array.
How It Works
As we scan each element in the array, we compare it against our current `max` and `secondMax`:
1. If the current element is greater than `max`: This means we've found a new largest element. The old `max` now becomes the new `secondMax`, and the current element becomes the new `max`. 2. If the current element is not greater than `max` but is greater than `secondMax`: This means the current element is the new second largest. We update `secondMax` to this element. 3. Otherwise: If the current element is smaller than or equal to `secondMax`, it is not relevant to our goal, and we simply move to the next element.
This process ensures that after a single pass, `max` will hold the largest element and `secondMax` will hold the second largest element in the array.
function findSecondMax(array):
if array.length < 2:
return error or handle appropriately
max = -infinity
secondMax = -infinity
for each element in array:
if element > max:
secondMax = max
max = element
else if element > secondMax and element != max:
secondMax = element
return secondMaxKey Takeaways
- Finding the second largest element efficiently avoids full array sorting.
- An O(n) approach involves a single pass through the array.
- Only two variables (`max` and `secondMax`) are needed to track the top two elements.
- Updates occur when a new largest or new second largest element is encountered.
- This method significantly reduces computational overhead compared to sorting.
Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.
Ask your own question →