Third Maximum Number
Easy
Topics
Given an integer array nums, return the third distinct maximum value. If it does not exist, return the maximum value.
Example 1
Input: nums = [3,2,1] Output: 1
Example 2
Input: nums = [1,2] Output: 2
Example 3
Input: nums = [2,2,3,1] Output: 1
Constraints
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
We want the third distinct maximum, falling back to the maximum when fewer than three distinct values exist. Deduplicating and sorting descending answers it directly in O(n log n), which is what the shown solution does.
The O(n) single-pass version tracks the three largest distinct values. It is more fiddly than it looks, and the fiddliness is the point of the problem: you must skip values equal to any tracker (so duplicates do not displace anything), and you must use a sentinel that cannot collide with real data — the values span the full signed 32-bit range, so -2^31 is a legitimate input and cannot double as "unset". Use None, or negative infinity, not Integer.MIN_VALUE.
Approach
- Deduplicate, sort descending.
- Return the third element if it exists, else the first.
Dry Run
nums = [3,2,1]
distinct sorted desc [3,2,1] -> third is 1
nums = [1,2]
distinct [2,1], fewer than three -> return the max, 2
nums = [2,2,3,1]
distinct [3,2,1] -> third is 1
(the duplicate 2 does not create a second rank)Complexity
- Time — O(n log n) for the sort; the three-tracker pass is O(n).
- Space — O(n) for the distinct set, which the claim states honestly. The three-tracker version is O(1), and that is the reason to prefer it if asked.
Common Pitfalls
- Forgetting that "maximum" means distinct.
[2,2,3,1]has third maximum 1, not 2. - Using
Integer.MIN_VALUEas the "unset" sentinel in the tracker version.-2^31is a valid input value, so a legitimate minimum would be mistaken for unset. - Returning the third largest element rather than the third largest distinct value.
- Returning null or -1 when fewer than three distinct values exist. The specified fallback is the maximum.
Full Solution — all languages
class Solution:
def thirdMax(self, nums):
s = sorted(set(nums), reverse=True)
return s[2] if len(s) >= 3 else s[0]import java.util.*;
class Solution {
public int thirdMax(int[] nums) {
TreeSet<Integer> set = new TreeSet<>();
for (int x : nums) set.add(x);
if (set.size() < 3) return set.last();
Iterator<Integer> it = set.descendingIterator();
it.next();
it.next();
return it.next();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int thirdMax(vector<int>& nums) {
set<int> s(nums.begin(), nums.end());
if (s.size() < 3) return *s.rbegin();
auto it = s.rbegin();
++it;
++it;
return *it;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var thirdMax = function(nums) {
const s = Array.from(new Set(nums)).sort((x, y) => y - x);
return s.length >= 3 ? s[2] : s[0];
};