Increasing Triplet Subsequence (LeetCode 334): Solution and Explanation
Given an integer array nums, decide whether three indices i < j < k exist with nums[i] < nums[j] < nums[k]. The elements can be far apart; only their order and values matter.
Intuition
A triplet needs a small value, then a bigger one after it, then a bigger one after that. Scanning left to right, the question at each element is: could this be the third value? That is true exactly when some earlier pair already rises and its top is below the current value.
Of all the rising pairs seen so far, only the one with the smallest top matters, because a smaller top is easier for a later value to beat. Call that top second. To keep second as small as possible, we also need the smallest value seen so far, first, since any later value above first could become a new, lower second.
So each element does one of three things. If it is not above first, it lowers first. If it is above first but not above second, it becomes the new second. If it is above second, we have a triplet.
The step that looks wrong is lowering first after second is set, because now first sits to the right of second. It is still fine: second was set when an older, smaller value was before it, and that value has not gone anywhere. first is only a candidate for building a future, lower pair.
Approach: Greedy with two thresholds
- Set
firstandsecondto infinity. - For each value
ninnums, ifn <= first, setfirst = n. - Otherwise, if
n <= second, setsecond = n. It now has a smaller value before it. - Otherwise
n > second, so a smaller value, thensecond, thennform a triplet. Return true. - If the loop ends, no value ever beat
second. Return false.
Step-by-step example
nums = [1,2,3,4,5]
- first and second start at infinity.
- n = 1 is not above first, so first = 1.
- n = 2 is above first (1) but not above second (infinity), so second = 2. The pair 1 < 2 now exists.
- n = 3 is above second (2). The triplet 1 < 2 < 3 at indices 0, 1, 2 is found, so return true.
Code: Python, Java, C++
1class Solution:
2 def increasingTriplet(self, nums: List[int]) -> bool:
3 first = second = float('inf')
4 for n in nums:
5 if n <= first:
6 first = n
7 elif n <= second:
8 second = n
9 else:
10 return True
11 return False1class Solution {
2 public boolean increasingTriplet(int[] nums) {
3 int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
4 for (int n : nums) {
5 if (n <= first) {
6 first = n;
7 } else if (n <= second) {
8 second = n;
9 } else {
10 return true;
11 }
12 }
13 return false;
14 }
15}1class Solution {
2public:
3 bool increasingTriplet(vector<int>& nums) {
4 int first = INT_MAX, second = INT_MAX;
5 for (int n : nums) {
6 if (n <= first) {
7 first = n;
8 } else if (n <= second) {
9 second = n;
10 } else {
11 return true;
12 }
13 }
14 return false;
15 }
16};Time and space complexity
O(n)
Each element is compared at most twice, and the scan stops as soon as a triplet appears.
O(1)
Only the two thresholds are stored.
Other approaches
Prefix minimum and suffix maximum (time O(n), space O(n))
Build an array of the smallest value to the left of each index and the largest value to the right. Any index whose value lies strictly between them is a valid middle. Simple to reason about but uses two extra arrays.
Longest increasing subsequence with patience sorting (time O(n log 3), space O(1))
Run the binary-search LIS algorithm and stop when the tails array reaches length 3. The two-threshold method is exactly this algorithm with the tails array capped at two entries.
Brute force (time O(n^3), space O(1))
Try every triple of indices. Correct but far too slow for 5 * 10^5 elements.
Common mistakes
- Using
<instead of<=in the comparisons. An equal value must not count as rising, so ties have to fall into the update branches, not the return branch. - Thinking
firstandsecondmust always be the actual triplet. Afterfirstdrops, the true pair behindseconduses an older value; the algorithm only needs to know that pair exists. - Initializing the thresholds with a sentinel that a real value can exceed. With
INT_MAXand<=comparisons the logic still holds, since no int is aboveINT_MAX.
Frequently asked questions
Why is it safe to overwrite first after second has been set?
second was set only when a smaller value came before it. That earlier value still exists in the array, so the pair behind second stays valid. The new first only matters for forming a lower second later.
How do I get the actual indices of the triplet?
Store the index of first, the index of second, and also the index first had at the moment second was set. When a value beats second, return that saved index, the index of second, and the current index.
Does this generalize to an increasing subsequence of length k?
Yes. Keep k - 1 thresholds, or use the LIS tails array with binary search and stop once it reaches length k. That runs in O(n log k).