Python 0414.py
class Solution:
def thirdMax(self, nums: List[int]) -> int:
all = set(nums)
if len(all) < 3:
return max(all)
all.remove(max(all))
all.remove(max(all))
return max(all)
Difficulty
and has an acceptance rate of about 39% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution.thirdMax method receives a list of integers and returns the third distinct maximum value when such a value exists. If the list contains fewer than three unique numbers, the method returns the greatest number among the distinct elements. The implementation relies on Python’s built-in set type to eliminate duplicates and on successive calls to max to isolate the required values.
Key Steps
Converting the Input List to a Set
The first operation creates a set from the input list, thereby discarding any repeated entries and leaving only the distinct integers.
all = set(nums)
This step guarantees that subsequent logic works with a collection of unique values, simplifying the determination of distinct maxima.
Determining Whether a Third Distinct Maximum Exists
Immediately after deduplication, the method checks the cardinality of the set. If fewer than three distinct numbers are present, the function returns the maximum element of the set, satisfying the requirement to fall back to the greatest value when a third distinct maximum cannot be identified.
if len(all) < 3:
return max(all)
Removing the Two Largest Distinct Values
When the set contains three or more unique numbers, the algorithm proceeds to eliminate the two greatest values. The first max(all) call identifies the largest element, which is then removed from the set. A second max(all) call, now operating on the reduced set, finds the next largest element, which is also removed.
all.remove(max(all))
all.remove(max(all))
These two removals ensure that only values smaller than the top two remain in the set.
Returning the Third Maximum Value
After the two largest distinct numbers have been removed, the remaining set contains the third distinct maximum as its greatest element. The final max call retrieves this value and returns it as the result.
return max(all)
Edge Cases Addressed
The implementation gracefully handles inputs where all elements are identical; the set reduces to a single element, the length check triggers the early return, and the sole value is returned. When the list contains exactly two distinct numbers, the length condition again causes an early return of the larger of the two, satisfying the specification for insufficient distinct values. Duplicate entries of any magnitude are eliminated by the initial set conversion, ensuring that the algorithm’s logic operates solely on unique values. Negative integers and very large integer values are treated identically to positive numbers because the max function operates correctly across the entire integer range.
Performance Optimizations
By converting the list to a set, the method removes duplicate values in a single pass, reducing the amount of data that subsequent operations must process. The use of Python’s built-in max function leverages highly optimized C-level loops, providing fast identification of the largest element without explicit iteration in Python code. Removing the two largest elements directly from the set avoids the need for sorting the entire collection, which would incur additional overhead. Consequently, the algorithm performs a constant number of passes over a collection whose size is bounded by the number of distinct elements, leading to efficient execution even for large input lists.
ELI5 - Simplified Explanation
Imagine a big basket full of colorful number blocks. The first thing this code does is empty the basket out onto the floor and pick out only the unique blocks so that no two blocks have the same number. If there are fewer than three blocks left after clearing out the duplicates, it simply looks for the biggest block and picks that one. If there are plenty of blocks, it performs a little game. It finds the largest block and takes it away. Then, it looks at the remaining pile, finds the largest block again, and takes that one away too. Finally, it looks at what is left in the pile and grabs the biggest block remaining, which is the third one you would find if you went in order from biggest to smallest.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Go | Python | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| Krazune | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| Krazune | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 215: Kth Largest Element in an Array
- problem 2733: Neither Minimum nor Maximum
Solved On The Same Day
- problem 342: Power of Four
- problem 344: Reverse String
- problem 345: Reverse Vowels of a String
- problem 349: Intersection of Two Arrays
- problem 350: Intersection of Two Arrays II
- problem 387: First Unique Character in a String
- problem 412: Fizz Buzz
- problem 434: Number of Segments in a String
- problem 448: Find All Numbers Disappeared in an Array
- problem 485: Max Consecutive Ones
- problem 504: Base 7
- problem 507: Perfect Number
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality