SDE & MLE Prep

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