Problem 334

Abstract / Summary

Determine if there are three numbers in the sequence that appear in increasing order.

Note

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

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
15 lines | 337 bytes | submitted September 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.89 | σ = 1.03

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++ 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++
45 links | 30 authors | 10 languages

Videos

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

Similar Problems

4 similar problems

Solved On The Same Day

11 solutions   September 11, 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