Skip to content
Problem 414 · LeetCode 414(opens in a new tab)

Third Maximum Number

EasyArrays

You are given an array of integers, nums. Look only at its distinct values, so repeats of a number count once. Return the third largest of those values.

If there are fewer than three distinct values, return the largest value instead.

Example 1

Input:  nums = [6, 2, 6, 9, 4]
Output: 4
Why:    the distinct values from the top are 9, 6, 4
2 more examples and the constraints

Example 2

Input:  nums = [5, 5]
Output: 5
Why:    only one distinct value, so return the largest

Example 3

Input:  nums = [-1, -2147483648, 3]
Output: -2147483648
Why:    3, then −1, then the smallest int

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Distinct values, sortedO(n log n)
  2. Track the top threeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 numbersVerdict
Distinct values, sortedO(n log n)
Passes; sorts far more than needed
Track the top threeO(n)
Best; one pass, no extra memory

n = length of nums.

Edge cases to test

  • Fewer than three distinct values. [5, 5] or [1, 2]: return the largest.
  • The smallest int as an answer. [-1, -2147483648, 3] returns −2,147,483,648, so the empty mark must be something else.
  • Repeats of the top values. [1, 2, 2, 5, 3, 5] has distinct values 5, 3, 2, 1, so the answer is 2.
  • One number. Return it.

Common mistakes

  • Counting a repeated value twice, so [2, 2, 3, 1] would give 2 instead of 1.
  • Using the smallest 32-bit int as "not set", which breaks when that value is in the array.
  • Returning the second largest, or −1, when there are fewer than three distinct values.

How to talk through it

  1. 1Clarify. Do repeats count once? What do I return with fewer than three distinct values? How small can values get?
  2. 2Give the simple version. Set, sort descending, take index 2 or index 0.
  3. 3Keep three slots. One pass; skip equals; shift the slots down when a bigger value arrives.
  4. 4Pick the empty mark. Use a long sentinel, −∞ or null, since the smallest int is a valid value.
  5. 5Test out loud. Run [6, 2, 6, 9, 4], [5, 5] and [-1, -2147483648, 3], and check 4, 5 and −2,147,483,648.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?