Third Maximum Number (LeetCode 414): Solution and Explanation
Return the third largest distinct value in nums. Duplicates count once. If fewer than three distinct values exist, return the largest value instead.
Intuition
Sorting the array descending and walking it while skipping repeats finds the answer, but it costs O(n log n) and the follow-up asks for linear time.
At any moment you only care about the three largest distinct values seen so far. Everything else can never become the answer, so three variables are enough memory.
Think of them as a podium. A new value either is already standing on it (skip), beats first (everyone moves down a place and the old third falls off), beats only second (old second drops to third), beats only third (it replaces third), or is too small to matter.
The one subtle part is the empty slot. The input can contain -2^31, so you cannot use the smallest int as a marker for empty. Use minus infinity, a 64-bit minimum, or a nullable value instead.
Approach: One pass with three slots
- Set
first,secondandthirdto a value below every possible input. - For each
xinnums, skip it if it equals any of the three slots. - If
x > first, shift:third = second,second = first,first = x. - Else if
x > second, shift:third = second,second = x. - Else if
x > third, setthird = x. - After the loop, return
thirdif it was filled, otherwise returnfirst.
Step-by-step example
nums = [3,2,1]
- Start with first, second and third all empty.
- x = 3 beats the empty first slot, so first = 3.
- x = 2 is below first but beats the empty second slot, so second = 2.
- x = 1 is below second but beats the empty third slot, so third = 1.
- Third is filled, so return 1.
Code: Python, Java, C++
1class Solution:
2 def thirdMax(self, nums: List[int]) -> int:
3 first = second = third = float('-inf')
4 for x in nums:
5 if x == first or x == second or x == third:
6 continue
7 if x > first:
8 first, second, third = x, first, second
9 elif x > second:
10 second, third = x, second
11 elif x > third:
12 third = x
13 return third if third != float('-inf') else first1class Solution {
2 public int thirdMax(int[] nums) {
3 long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
4 for (int x : nums) {
5 if (x == first || x == second || x == third) {
6 continue;
7 }
8 if (x > first) {
9 third = second;
10 second = first;
11 first = x;
12 } else if (x > second) {
13 third = second;
14 second = x;
15 } else if (x > third) {
16 third = x;
17 }
18 }
19 return (int) (third == Long.MIN_VALUE ? first : third);
20 }
21}1class Solution {
2public:
3 int thirdMax(vector<int>& nums) {
4 long long first = LLONG_MIN, second = LLONG_MIN, third = LLONG_MIN;
5 for (int x : nums) {
6 if (x == first || x == second || x == third) {
7 continue;
8 }
9 if (x > first) {
10 third = second;
11 second = first;
12 first = x;
13 } else if (x > second) {
14 third = second;
15 second = x;
16 } else if (x > third) {
17 third = x;
18 }
19 }
20 return (int) (third == LLONG_MIN ? first : third);
21 }
22};Time and space complexity
O(n)
Each element is compared with at most three slots and moved at most once, so the scan is linear.
O(1)
Only three slot variables are kept, no matter how long the array is.
Other approaches
Sort and walk distinct values (time O(n log n), space O(1))
Sort descending, then walk the array counting each new distinct value. Return the third one, or the first if you run out. Easy to write but slower.
Set plus min-heap of size 3 (time O(n log 3) = O(n), space O(n) for the seen set)
Push each distinct value into a min-heap and pop whenever it grows past three. The heap top is the third maximum. This generalises to the k-th maximum.
Common mistakes
- Using
Integer.MIN_VALUEas the empty marker. For [1,2,-2147483648] the true answer is -2147483648, and the marker would make it look like third is empty. - Forgetting to skip duplicates. In [2,2,3,1] the two 2s must count once, or the answer would wrongly be 2.
- Shifting in the wrong order. Move third first, then second, then write the new value, or you overwrite something you still need.
- Returning the second maximum when only two distinct values exist. The fallback is the maximum, not the second largest.
Frequently asked questions
Why return the maximum when there are fewer than three distinct values?
That is the rule the problem sets. With one or two distinct values a third maximum does not exist, so the largest value is returned instead.
Why are long or 64-bit slots used in Java, C++ and C#?
So the empty marker sits strictly below -2^31. Every real input fits in 32 bits, so an empty slot can never be confused with a real value.
How would you find the k-th maximum distinct value?
Keep a min-heap of size k over distinct values (with a set to skip repeats). After the scan, the heap top is the k-th maximum if the heap is full.