Increasing Triplet Subsequence - Problem
You're given an integer array nums, and your task is to determine if there exists an increasing triplet subsequence.
Specifically, you need to find three indices i, j, and k such that:
i < j < k(indices are in order)nums[i] < nums[j] < nums[k](values are strictly increasing)
Return true if such a triplet exists, false otherwise.
Key insight: You don't need to find the actual triplet - just determine if one exists! This opens up opportunities for space-efficient solutions.
Example: In array [1, 2, 3, 4, 5], we can pick indices 0, 1, 2 where 1 < 2 < 3, so return true.
Input & Output
example_1.py β Basic Increasing Sequence
$
Input:
[1,2,3,4,5]
βΊ
Output:
true
π‘ Note:
Multiple valid triplets exist: (1,2,3), (1,2,4), (2,3,4), etc. Any three consecutive or non-consecutive elements work since the array is strictly increasing.
example_2.py β No Valid Triplet
$
Input:
[5,4,3,2,1]
βΊ
Output:
false
π‘ Note:
Array is strictly decreasing, so no increasing triplet can exist. Every element is smaller than the previous ones.
example_3.py β Mixed Pattern
$
Input:
[2,1,1,0,4,2,6]
βΊ
Output:
true
π‘ Note:
Valid triplet exists: indices (3,4,6) give us values (0,4,6) where 0 < 4 < 6. The key insight is that we don't need consecutive elements.
Visualization
Tap to expand
Understanding the Visualization
1
Deploy Scouts
Start with both scouts at 'infinity height' - they haven't found any peaks yet
2
First Scout Updates
When you find a peak lower than first scout's peak, send first scout there
3
Second Scout Updates
When you find a peak higher than first but lower than second, send second scout there
4
Victory Condition
When you find any peak higher than second scout's position, you've found your ascending triplet!
Key Takeaway
π― Key Insight: By maintaining the most promising 'first' and 'second' candidates, we can detect any increasing triplet in a single pass without storing the entire sequence!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, each element processed once
β Linear Growth
Space Complexity
O(1)
Only using two variables regardless of input size
β Linear Space
Constraints
- 1 β€ nums.length β€ 5 Γ 105
- -231 β€ nums[i] β€ 231 - 1
- Follow-up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code