Problem 414

Abstract / Summary

Find the third highest distinct number in a list or return the highest if there are fewer than three.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
9 lines | 233 bytes | submitted August 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 39% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 6.31 | σ = 0.61

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
36 links | 24 authors | 9 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

12 easy
13 solutions   August 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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