334. Increasing Triplet Subsequence
Problem
Decide whether there are indices i < j < k with nums[i] < nums[j] < nums[k].
Example: [2,1,5,0,4,6] → true; [5,4,3,2,1] → false
Constraints: n ≤ 5·10⁵. Follow-up: O(n) time and O(1) space.
Keep the smallest possible first element and the smallest possible second element of an increasing pair seen so far. Any number bigger than both completes a triplet. (Updating first after second is set is fine: second still certifies that some smaller element came before it.)
Complexity: O(n) time, O(1) space.
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first = second = float("inf")
for x in nums:
if x <= first:
first = x
elif x <= second:
second = x
else:
return True
return False
assert Solution().increasingTriplet([1, 2, 3, 4, 5]) is True
assert Solution().increasingTriplet([5, 4, 3, 2, 1]) is False
assert Solution().increasingTriplet([2, 1, 5, 0, 4, 6]) is True
assert Solution().increasingTriplet([20, 100, 10, 12, 5, 13]) is True
assert Solution().increasingTriplet([1, 1, 1]) is False
assert Solution().increasingTriplet([1, 5, 0, 4, 1, 3]) is True
class Solution {
public boolean increasingTriplet(int[] nums) {
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int x : nums) {
if (x <= first) first = x;
else if (x <= second) second = x;
else return true;
}
return false;
}
}
func increasingTriplet(nums []int) bool {
first, second := math.MaxInt, math.MaxInt // smallest end of increasing runs of length 1 and 2
for _, x := range nums {
if x <= first {
first = x
} else if x <= second {
second = x
} else {
return true
}
}
return false
}