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
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
โ Linear Growth
Space Complexity
O(1)
Only using three variables regardless of input size
โ Linear Space
Constraints
- 1 โค nums.length โค 104
- -231 โค nums[i] โค 231 - 1
- Follow up: Can you find an O(n) time complexity solution?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code