Detect a Strictly Increasing Triplet

medium array greedy

Problem

Decide whether three indices i < j < k exist such that nums[i] < nums[j] < nums[k]. Track two running values: the smallest seen so far (first) and the smallest seen that is still bigger than something earlier (second). Any value greater than second closes a triplet.

Inputnums = [6, 1, 5, 2, 8]
Outputtrue
first=1, second=2, then 8 > 2 → triplet (1, 2, 8) exists.

def increasing_triplet(nums):
    first = second = float('inf')
    for x in nums:
        if x <= first: first = x
        elif x <= second: second = x
        else: return True
    return False
function increasingTriplet(nums) {
  let first = Infinity, second = Infinity;
  for (const x of nums) {
    if (x <= first) first = x;
    else if (x <= second) second = x;
    else return true;
  }
  return false;
}
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;
    }
}
bool increasingTriplet(vector<int>& nums) {
    int first = INT_MAX, second = INT_MAX;
    for (int x : nums) {
        if (x <= first) first = x;
        else if (x <= second) second = x;
        else return true;
    }
    return false;
}
Time: O(n) Space: O(1)