Third Maximum Number

Easy

Topics
ArraySorting

Given an integer array nums, return the third distinct maximum value. If it does not exist, return the maximum value.

Example 1

302112
Duplicates do not count as separate maxima, so the ranking runs over distinct values: 3 > 2 > 1. The third is 1.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [3,2,1]
Output: 1

Example 2

1021
There are only 2 distinct value(s), so no third maximum exists and the answer falls back to the largest, 2.
Input:  nums = [1,2]
Output: 2

Example 3

20213213
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

  1. Deduplicate, sort descending.
  2. 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_VALUE as the "unset" sentinel in the tracker version. -2^31 is 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]
SensAI
Beta
Tap the mic to stop voice mode