Checking for increasing triplet in JavaScript


Increasing Numbers:

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

We are required to write a JavaScript function that takes in an array of Numbers, arr, as the only argument. The function should check whether there exist three consecutive elements in the array that are increasing.

For example, if the input to the function is −

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

Then the output should be −

const output = true;

Output Explanation:

Because there exists 1, 5, 7 in the array consecutively,

Example

The code for this will be −

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));

Code Explanation:

The condition we have check for in each iteration of our loop is −

We return true if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 otherwise we return false.

Output

And the output in the console will be −

true

Updated on: 19-Mar-2021

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements