LeetCode Solutions

334. Increasing Triplet Subsequence

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  bool increasingTriplet(vector<int>& nums) {
    int first = INT_MAX;
    int second = INT_MAX;

    for (const int num : nums)
      if (num <= first)
        first = num;
      else if (num <= second)  // First < num <= second
        second = num;
      else
        return true;  // First < second < num (third)

    return false;
  }
};
			

class Solution {
  public boolean increasingTriplet(int[] nums) {
    int first = Integer.MAX_VALUE;
    int second = Integer.MAX_VALUE;

    for (final int num : nums)
      if (num <= first)
        first = num;
      else if (num <= second) // First < num <= second
        second = num;
      else // First < second < num (third)
        return true;

    return false;
  }
}
			

class Solution:
  def increasingTriplet(self, nums: List[int]) -> bool:
    first = math.inf
    second = math.inf

    for num in nums:
      if num <= first:
        first = num
      elif num <= second:  # First < num <= second
        second = num
      else:
        return True  # First < second < num (third)

    return False