Increasing Triplet Subsequence Problem
Description
LeetCode Problem 334.
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.
Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Constraints:
- 1 <= nums.length <= 5 * 10^5
- -2^31 <= nums[i] <= 2^31 - 1
Solution
Approach: Track the Two Smallest Ends
Checking all triples is O(n3). Instead, scan once and keep two values:
first: the smallest number seen so far.second: the smallest number seen so far that has some smaller number before it, i.e. the smallest possible end of an increasing pair.
For each x:
- If
x <= first, it becomes the newfirst. - Otherwise, if
x <= second, thenfirst < x, soxends a pair: it becomes the newsecond. - Otherwise
x > second, and the pair thatsecondends, followed byx, is an increasing triplet: returntrue.
Keeping both values as small as possible makes it as easy as possible for a later number to extend them, so if a triplet exists, step 3 will fire.
The part that looks wrong but is fine: when first is replaced by a smaller value that comes after second, the two no longer form a pair in order. That does not matter, because second only records that some smaller value appeared before it. In [2, 5, 0, 6], after 0 we have first = 0 and second = 5, and 6 > 5 is still a real triplet (2, 5, 6).
Use <=, not <, so equal numbers never count as increasing.
Complexity: O(n) time, where n is the length of nums, and O(1) space.
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = float("inf") # smallest value seen so far
second = float("inf") # smallest value that has a smaller value before it
for x in nums:
if x <= first:
first = x
elif x <= second:
second = x # first < x, so (first, x) is an increasing pair
else:
return True # x > second > (some earlier value)
return False
Now write it from memory
Close the write-up and solve it yourself against the tests.