How to use single-pass comparison In Javascript

To ascertain whether the array is monotonic, this method traverses the array once and compares each element with its neighbouring element. As it loops over the array, it updates the two flags it maintains—one for non-increasing and one for non-decreasing.

Example: Function to determine if an array is either entirely non-increasing or non-decreasing, providing a quick monotonicity check.

Javascript




function isMonotonic(array) {
    let isNonIncreasing = true;
    let isNonDecreasing = true;
 
    for (let i = 1; i < array.length; i++) {
        if (array[i] > array[i - 1]) {
            isNonIncreasing = false;
        }
        if (array[i] < array[i - 1]) {
            isNonDecreasing = false;
        }
    }
 
    return isNonIncreasing || isNonDecreasing;
}
 
console.log(isMonotonic([1, 2, 2, 4]));
console.log(isMonotonic([3, 2, 5]));
console.log(isMonotonic([1, 3, 9]));


Output

true
false
true

Check if Given Array is Monotonic in JavaScript

To determine whether an array is monotonic that is completely non-increasing or non-decreasing an array should have members ordered either ascending or descending in a direction-neutral fashion that is called monotone. A successful solution to this problem can simplify several algorithmic tasks.

In JavaScript, there are several ways to determine if an array is monotonic or not which are as follows:

Table of Content

  • Using single-pass comparison
  • Using sorting
  • Using set comparison
  • Using functional programming
  • Using recursion
  • Using Math(Sign Analysis):-

Similar Reads

Using single-pass comparison

To ascertain whether the array is monotonic, this method traverses the array once and compares each element with its neighbouring element. As it loops over the array, it updates the two flags it maintains—one for non-increasing and one for non-decreasing....

Using sorting

...

Using set comparison

The array’s elements are initially rearranged in either ascending or descending order by sorting the array. Then you can check if it’s monotonic by comparing the sorted array with the original. However, because of sorting, this method modifies the original array and has an O(n log n) time complexity....

Using functional programming

...

Using recursion

Duplicates are immediately eliminated by turning the array into a Set, leaving unique elements. You can find out if the array is monotonic by looking at the size of the generated Set. Nevertheless, this method necessitates extra room in line with the array’s size....

Using Math(Sign Analysis)

...