# 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.

Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5]
Output: true

Example 2:

Input: [5,4,3,2,1]
Output: false

# Solution

Approach 1: O(nlogn).

Approach 2: O(n) by tracking the mininum and the second mininum elements.

# Code (Python)

Approach 1:

Approach 2:

# Code (C++)

Approach 1:

// O(nlogn) time.
class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        vector<int> buf;
        for (int i = 0; i < nums.size(); ++i)
        {
            int lo = 0;
            int hi = buf.size() - 1;
            while (lo <= hi)
            {
                int mid = lo + (hi - lo) / 2;
                if (nums[i] < buf[mid])
                    hi = mid - 1;
                else if (nums[i] > buf[mid])
                    lo = mid + 1;
                else
                    break;
            }
            if (lo > (int)buf.size() - 1)
                buf.push_back(nums[i]);
            else if (lo > hi)
                buf[lo] = nums[i];
        }
        return buf.size() >= 3;
    }
};

Approach 2:

// O(n) time.
class Solution {
public:
    bool increasingTriplet(vector<int>& nums) {
        int min1Idx = 0;
        int min2Idx = -1;
        for (int i = 1; i < nums.size(); ++i)
        {
            if (min2Idx >= 0 && nums[i] > nums[min2Idx])
                return true;

//            else if (nums[i] <= nums[min1Idx])
//                min1Idx = i;
//            else if (min2Idx < 0 || nums[i] < nums[min2Idx])
//                min2Idx = i;

            else if (nums[i] > nums[min1Idx])
                min2Idx = i;
            else if (nums[i] < nums[min1Idx])
                min1Idx = i;
        }
        return false;
    }
};