Third Maximum Number (LeetCode 414): Solution and Explanation

Easy
Array
Sorting

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

  1. Set first, second and third to a value below every possible input.
  2. For each x in nums, skip it if it equals any of the three slots.
  3. If x > first, shift: third = second, second = first, first = x.
  4. Else if x > second, shift: third = second, second = x.
  5. Else if x > third, set third = x.
  6. After the loop, return third if it was filled, otherwise return first.

Step-by-step example

nums = [3,2,1]
  1. Start with first, second and third all empty.
  2. x = 3 beats the empty first slot, so first = 3.
  3. x = 2 is below first but beats the empty second slot, so second = 2.
  4. x = 1 is below second but beats the empty third slot, so third = 1.
  5. 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 first
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element is compared with at most three slots and moved at most once, so the scan is linear.

Space

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_VALUE as 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.