Third Maximum Number - Problem

You're given an integer array nums, and your task is to find the third distinct maximum number in the array. Think of it like finding the bronze medalist in a competition!

Here's the catch: if there aren't three distinct maximum numbers (i.e., the array has fewer than 3 unique values), you should return the maximum number instead.

Key Points:

  • We need distinct maximums - duplicates don't count as separate maximums
  • If third maximum exists โ†’ return it
  • If third maximum doesn't exist โ†’ return the overall maximum

Example: In array [3, 2, 1], the first max is 3, second max is 2, and third max is 1, so we return 1. But in [1, 2], there's no third distinct maximum, so we return the maximum which is 2.

Input & Output

example_1.py โ€” Standard Case
$ Input: nums = [3, 2, 1]
โ€บ Output: 1
๐Ÿ’ก Note: The first distinct maximum is 3, second is 2, and third is 1. Since we have three distinct maximums, we return the third one which is 1.
example_2.py โ€” Insufficient Distinct Values
$ Input: nums = [1, 2]
โ€บ Output: 2
๐Ÿ’ก Note: We only have two distinct values (1 and 2), so there's no third distinct maximum. Therefore, we return the maximum value which is 2.
example_3.py โ€” Array with Duplicates
$ Input: nums = [2, 2, 3, 1]
โ€บ Output: 1
๐Ÿ’ก Note: The distinct values are [3, 2, 1]. The third distinct maximum is 1. Note that duplicate 2's are treated as a single distinct value.

Visualization

Tap to expand
๐Ÿ† Olympic Medal Podium - Third Maximum๐Ÿฅ‰ 3rd1๐Ÿฅ‡ 1st3๐Ÿฅˆ 2nd2ResultBronze = 1Input: [3, 2, 1, 1, 2]Process: Gold=3, Silver=2, Bronze=1Skip duplicates: 1, 2 (already on podium)Return: Bronze medalist = 1
Understanding the Visualization
1
Initialize Podium
Set up three empty podium positions: Gold (1st), Silver (2nd), Bronze (3rd)
2
Process Each Score
For each athlete's score, check if it deserves a podium position and update accordingly
3
Handle Ties
Skip duplicate scores as they represent the same performance level
4
Award Bronze
If we have a bronze medalist, return their score; otherwise, return the gold medalist's score
Key Takeaway
๐ŸŽฏ Key Insight: We only need to track the top 3 distinct values, not sort the entire array. This reduces time complexity from O(n log n) to O(n) while using constant space!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array, each element processed in constant time

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using three variables regardless of input size

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -231 โ‰ค nums[i] โ‰ค 231 - 1
  • Follow up: Can you find an O(n) time complexity solution?
Asked in
Amazon 15 Google 8 Microsoft 6 Apple 4
78.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen