Increasing Triplet Subsequence LeetCode Solution

Last updated on July 18th, 2024 at 03:45 am

Here, We see Increasing Triplet Subsequence LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Array

Companies

Facebook

Level of Question

Medium

Increasing Triplet Subsequence LeetCode Solution

Increasing Triplet Subsequence LeetCode Solution

Problem Statement

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

Example 1:
Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.

Example 2:
Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.

Example 3:
Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

1. Increasing Triplet Subsequence LeetCode Solution C++

class Solution {
public:
   bool increasingTriplet(vector&lt;int&gt;&amp; nums) {
    int n=nums.size();
    if(n&lt;3)return false;
    int low=INT_MAX, mid=INT_MAX;
    for(int i=0;i&lt;n;i++)
    {
        if(nums[i]&gt;mid) return true;
        else if(nums[i]&lt;low) low=nums[i];
        else if(nums[i]&gt; low and nums[i]&lt;mid) mid=nums[i];
    }
                return false;
    }
};

2. Increasing Triplet Subsequence LeetCode Solution Java

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;
        for(int num : nums){
            if(num &lt;= min) min = num;
            else if(num &lt; secondMin) secondMin = num;
            else if(num &gt; secondMin) return true;
        }
        return false;        
    }
}

3. Increasing Triplet Subsequence Solution JavaScript

var increasingTriplet = function(nums) {
    let firstNumber = Infinity;
    let secondNumber = Infinity;
    for (let currentNumber of nums) {
        if (currentNumber &gt; secondNumber &amp;&amp; currentNumber &gt; firstNumber) {
        return true;
        }
        if (currentNumber &gt; firstNumber) {
        secondNumber = currentNumber;
        } else {
        firstNumber = currentNumber;
        }
    }
    return false;    
};

4. Increasing Triplet Subsequence Solution Python

class Solution(object):
    def increasingTriplet(self, nums):
        first = second = float('inf')
        for n in nums:
            if n &lt;= first:
                first = n
            elif n &lt;= second:
                second = n
            else:
                return True
        return False
Scroll to Top