Checking for increasing triplet in JavaScript

In JavaScript, an increasing triplet refers to three numbers in an array where each number is greater than the previous one, appearing in sequence (not necessarily consecutive positions).

Understanding Increasing Sequences

A sequence of numbers in which each succeeding element is either greater or equal to the preceding element is an increasing sequence.

For instance:

4, 6, 8, 9, 11, 14 is increasing sequence
3, 3, 3, 3, 3, 3, 3 is also an increasing sequence

Problem Statement

We need to write a JavaScript function that takes an array of numbers and checks whether there exist three elements in the array that form an increasing triplet (arr[i] < arr[j] < arr[k] where i < j < k).

For example, if the input array is:

const arr = [4, 1, 5, 7, 3, 1, 4];

The output should be true because there exists the subsequence 1, 5, 7 in increasing order.

Algorithm Explanation

We use a two-pointer approach to track the smallest and second smallest values seen so far. If we find a third value greater than both, we have found our increasing triplet.

Increasing Triplet Detection 4 1 5 7 3 1 4 first=4 first=1 second=5 Found! Increasing Triplet: 1 < 5 < 7 First (smallest) Second (middle) Third (largest)

Implementation

const arr = [4, 1, 5, 7, 3, 1, 4];

const increasingTriplet = function(arr) {
    let first = Infinity;
    let second = Infinity;
    
    for (let curr of arr) {
        if (curr > second && curr > first) {
            return true;
        }
        if (curr > first) {
            second = curr;
        } else {
            first = curr;
        }
    }
    return false;
};

console.log(increasingTriplet(arr));
true

How It Works

The algorithm maintains two variables:

  • first: The smallest number seen so far
  • second: The smallest number greater than first

When we encounter a number greater than both first and second, we have found our increasing triplet.

Additional Example

// Example with no increasing triplet
const arr2 = [5, 4, 3, 2, 1];
console.log(increasingTriplet(arr2));

// Example with increasing triplet at the end
const arr3 = [20, 100, 10, 12, 5, 13];
console.log(increasingTriplet(arr3));
false
true

Time Complexity

This solution has O(n) time complexity and O(1) space complexity, making it optimal for this problem.

Conclusion

The increasing triplet problem can be efficiently solved using a two-pointer approach that tracks the smallest and second smallest values. This algorithm finds any three numbers in increasing order with optimal time and space complexity.

Updated on: 2026-03-15T23:19:00+05:30

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements