Skip to content

Third Maximum Number

LeetCode 414 · Easy

Return the third-largest distinct integer. If fewer than three distinct values exist, return the largest.

Input Output Reason
[3, 2, 1] 1 Three distinct values
[1, 2] 2 Third value is absent
[2, 2, 3, 1] 1 Repeated 2 counts once

A fixed number of running maxima. Each new number enters at most one rank; displaced candidates shift down.

After each iteration, the three variables hold the largest three distinct values seen so far. Missing ranks use negative infinity, which is outside this problem’s integer domain. Shift lower ranks before replacing the higher ones.

Implement: submitted Python solution
class Solution:
def thirdMax(self, nums: list[int]) -> int:
largest = float('-inf')
largest2 = float('-inf')
largest3 = float('-inf')
for num in nums:
if num > largest:
largest3 = largest2
largest2 = largest
largest = num
elif largest > num:
if num > largest2:
largest3 = largest2
largest2 = num
elif largest2 > num and num > largest3:
largest3 = num
return largest if largest3 == float('-inf') else largest3
Next number First Second Third
2 2 missing missing
2 2 missing missing
3 3 2 missing
1 3 2 1

Strict comparisons exclude duplicates. Returning the maximum when the third rank is missing is part of this problem’s contract.

Write ranges from smallest to largest:

lower < candidate < upper
# means:
lower < candidate and candidate < upper

With largest = 10, largest2 = 6, and num = 8:

largest2 < num < largest # 6 < 8 < 10: True
largest > num > largest2 # 10 > 8 > 6: True
largest > num and num > largest2 # also True
largest < num < largest2 # 10 < 8 < 6: False

Use num for one item, and nums for the whole list.

O(n) time, O(1) auxiliary space. Three variables use constant storage: O(3) simplifies to O(1).

Why must the previous second move into third before the second variable is replaced? Trace a duplicate maximum and an input containing only two distinct values.

Study record: acceptance was reported by the learner. Implementation was reviewed by inspection; comparison direction was clarified afterward. This is not an independently observed LeetCode submission.