Python 0334.py
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
one = nums[0]
two = float("+inf")
for n in nums:
if n > two:
return True
if n <= one:
one = n
elif n < two:
two = n
return False
Difficulty
and has an acceptance rate of about 40% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
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 class implements a method that determines whether a given list of integers contains an increasing subsequence of length three. The algorithm scans the list once, maintaining two candidate values that represent the smallest and the second-smallest elements seen so far in a potential triplet. If a later element exceeds the second candidate, the method concludes that a valid increasing triplet exists and returns True; otherwise it finishes the scan and returns False.
Key Steps
Initialization
At the start, the algorithm stores the first element of the input as the initial smallest candidate and sets the second candidate to positive infinity, representing an unattainable upper bound.
one = nums[0]
two = float("+inf")
Iteration over the input
The method iterates through each number n in the list, evaluating it against the two candidates.
for n in nums:
Early termination condition
If the current number is larger than the second candidate, the algorithm has identified three numbers in strictly increasing order and can immediately return True.
if n > two:
return True
Updating the smallest and second smallest candidates
When the early exit does not trigger, the algorithm updates the candidates.
If the current number is less than or equal to the smallest candidate, it replaces that candidate, ensuring one always holds the minimal value encountered.
If the current number lies strictly between the smallest and the second candidate, it becomes the new second candidate, tightening the bound for a possible third element.
if n <= one:
one = n
elif n < two:
two = n
Final result
If the loop completes without finding a number greater than the second candidate, the method returns False, indicating that no increasing triplet exists in the input.
return False
Edge Cases Handled
The algorithm gracefully handles a list containing a single element because the loop runs but never satisfies the early exit condition, resulting in False.
When all elements are equal, the condition n <= one continuously updates one while two remains at infinity, so the method correctly returns False.
A strictly decreasing sequence never triggers the n > two check, and the candidates are repeatedly updated to the smallest seen value, again leading to a False result.
The use of float("+inf") ensures that any finite integer will be considered smaller than the initial second candidate, allowing the algorithm to correctly initialize the second bound even when the list contains very large positive numbers.
Performance Optimizations
The method processes the input in a single pass, avoiding nested loops or additional data structures. By maintaining only two scalar variables, it keeps the auxiliary memory footprint minimal. The early termination check (n > two) allows the function to stop scanning as soon as a valid triplet is detected, which can save considerable work on long inputs where the condition is met early. The choice of float("+inf") as the initial value for the second candidate eliminates the need for special-case handling of uninitialized state, streamlining the update logic.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy blocks. This code is like a little robot helper that walks down the row looking for three blocks that get bigger and bigger as they go.
The robot keeps two secret spots in its pockets to remember special numbers. The first spot holds the smallest number the robot has found so far. The second spot holds a medium-sized number that is bigger than the first one but smaller than anything else it has seen.
As the robot looks at each block in the row, it checks to see if the current block is even bigger than the number in the second pocket. If it finds a block that is larger than the medium one, it means it has successfully found a small block, a bigger block before it, and now a third block that is the biggest of all.
If the number it is holding is smaller than the smallest one it knows about, it updates its first pocket. If the number is not that small, it might put it in the second pocket if it fits better than the number currently there. The robot keeps doing this for every block in the row until it sees that perfect pattern of three increasing numbers.
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++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 300: Longest Increasing Subsequence
- problem 1995: Count Special Quadruplets
- problem 2179: Count Good Triplets in an Array
- problem 2552: Count Increasing Quadruplets
Solved On The Same Day
- problem 643: Maximum Average Subarray I
- problem 1431: Kids With the Greatest Number of Candies
- problem 310: Minimum Height Trees
- problem 355: Design Twitter
- problem 368: Largest Divisible Subset
- problem 382: Linked List Random Node
- problem 398: Random Pick Index
- problem 1004: Max Consecutive Ones III
- problem 1318: Minimum Flips to Make a OR b Equal to c
- problem 1679: Max Number of K-Sum Pairs
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