#334
Increasing Triplet Subsequence
MediumArrayGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach to keep track of the smallest and the second smallest numbers found so far. This allows us to determine if a third number can form a triplet without needing to check every combination.
⚙️
Algorithm
6 steps- 1Step 1: Initialize two variables, first and second, to infinity.
- 2Step 2: Loop through each number in the array.
- 3Step 3: If the current number is less than or equal to first, update first.
- 4Step 4: If the current number is greater than first but less than or equal to second, update second.
- 5Step 5: If the current number is greater than second, return true (we found a triplet).
- 6Step 6: If the loop completes without finding a triplet, return false.
solution.py11 lines
1# Full working Python code
2first = float('inf')
3second = float('inf')
4for num in nums:
5 if num <= first:
6 first = num
7 elif num <= second:
8 second = num
9 else:
10 return True
11return Falseℹ
Complexity note: This approach runs in O(n) time because we only make a single pass through the array, and it uses O(1) space since we only store a fixed number of variables.
- 1Understanding the difference between brute force and optimal solutions is crucial.
- 2Recognizing patterns in problems can lead to more efficient algorithms.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.