Third Maximum Number
Given an integer array nums, return the third distinct maximum number in this array. If the third distinct maximum does not exist, return the maximum number. Track three variables — first, second, and third — in a single pass , updating them as you scan so the largest, second largest, and third largest distinct values are always up to date.
Constraints
- 1 ≤ nums.length ≤ 104
- -231 ≤ numsi ≤ 231 - 1
Example
nums = [3, 2, 1]1Explanation The distinct maximums are 3, 2, then 1 — the third maximum is 1.
Track the top three distinct values in one pass
value=3. No trackers set yet, so first=3.
What happens in this step
value = nums[0] = 3 first, second, third are all unset 3 becomes first.
Steps to visualize
- Keep three trackers: first, second, and third, all starting as "not set".
- For each number, skip it if it equals a tracker already holding that exact value.
- If it is bigger than first, shift first down to second, second down to third, and this becomes first.
- Otherwise place it into second or third similarly if it fits between the current trackers.
- At the end, return third if it was set, otherwise return first.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
value=3. No trackers set yet, so first=3.
What happens in this step
value = nums[0] = 3 first, second, third are all unset 3 becomes first.
Solution
function thirdMax(nums) {
let first = null;
let second = null;
let third = null;
for (const value of nums) {
if (value === first || value === second || value === third) {
continue;
}
if (first === null || value > first) {
third = second;
second = first;
first = value;
} else if (second === null || value > second) {
third = second;
second = value;
} else if (third === null || value > third) {
third = value;
}
}
return third === null ? first : third;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [3, 2, 1] | 1 | example from the docstring |
nums = [1, 2] | 2 | fewer than three distinct values, falls back to the maximum |
nums = [2, 2, 3, 1] | 1 | duplicate values are ignored when tracking distinct maximums |
nums = [5] | 5 | smallest valid input, only one distinct value |
nums = [7, 7, 7] | 7 | every element is identical, only one distinct value exists |
nums = [-1, -2, -3, -4] | -3 | negative values with a proper third distinct maximum |