Computer >> Computer tutorials >  >> Programming >> Javascript

Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript


Suppose, we have an array of numbers like this −

const arr = [4, 7, 4, 8, 9, 3];

We are required to write a JavaScript function that takes in one such array of numbers. The function should search for such three numbers from the array whose indices as well as their magnitude is in the strictly increasing order (consecutive or non-consecutive).

For example, in the above array, the numbers 7, 8 and 9 have index 1, 3 and 4. These numbers satisfy both the conditions, so our function should return true for this array.

Example

The code for this will be −

const arr = [4, 7, 4, 8, 9, 3];
const findMatch = (arr) => {
   let stack = [];
   let s3 = −Infinity
   for (let i = arr.length − 1; i >= 0; i−−) {
      if (arr[i] < s3) return true
      while (stack.length > 0 && stack[stack.length − 1] < arr[i]) {
         s3 = stack.pop()
      };
      stack.push(arr[i])
   };
   return false
};
console.log(findMatch(arr));

Output

And the output in the console will be −

false