334 Increasing Triplet Subsequence

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should: Return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false. Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:

Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

The Idea: One way to approach this to two keep two placeholders. One will take the place of the first element that has an increasing sequence, two will take the place of element that follows if it is greater than than the first. If nothing else applies then we can return true, since the third element is greater than both and both elements two and three follow to be after one. Otherwise, the system will reset itself as smaller element arrive. We need <= for the uniform case; for example [1,1,1,1...1].

Complexity: O(n) time and O(1) space

bool increasingTriplet(vector<int>& nums) {
    int one = INT_MAX, two = INT_MAX;

    for (int i : nums) {            // sequential search ensures that index(one) < index(two) ...
        if (i <= one) one = i;      // the smallest since first if statement
        else if (i <= two) two = i; // second smallest
        else return true;           // finish
    }

    return false;
}

Last updated