DEV Community

Cover image for monotonic array
chandra penugonda
chandra penugonda

Posted on • Edited on

monotonic array

This problem was asked by Facebook.

A monotonic array is an array whose elements, from left to right, are entirely non increasing, or entirely non decreasing. Return true if the given array is monotonic.

Example
function monotonicArray(arr){

}

const arr = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
console.log(monotonicArray(arr)) // true
Enter fullscreen mode Exit fullscreen mode

Solution

function monotonicArray(arr) {
  let increasing = true,
    decreasing = true;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      increasing = false;
    } else if (arr[i] < arr[i + 1]) {
      decreasing = false;
    }
  }
  return increasing || decreasing;
}

const arr = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001];
console.log(monotonicArray(arr)); // true
Enter fullscreen mode Exit fullscreen mode

- This checks the array in O(n) time complexity by going through the elements sequentially and keeping track if the elements are either entirely increasing or decreasing.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay