Skip to content

Commit

Permalink
*
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed Jan 2, 2024
1 parent 419e34b commit 0077bc9
Showing 1 changed file with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Write a function that takes in an array of integers and returns a boolean
* representing whether the array is monotonic.
* An array is said to be monotonic if its elements, from left to right, are
* entirely non-increasing or entirely non-decreasing.
* Non-increasing elements aren't necessarily exclusively decreasing; they
* simply don't increase. Similarly, non-decreasing elements aren't necessarily
* exclusively increasing; they simply don't decrease.
* Note that empty arrays and arrays of one element are monotonic.
*
* Input:
* array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001]
*
* Output:
* true
*/

// Runtime: O(N), N = array length
// Space: O(1)

function isMonotonic(array) {
let num = array[0];
let upward;

for (let index = 1; index < array.length; index++) {
if (upward === undefined) {
upward = array[index] !== num ? array[index] > num : undefined;
}

if (upward !== undefined && upward && array[index] < num) {
return false;
}

if (upward !== undefined && !upward && array[index] > num) {
return false;
}

num = array[index];
}

return true;
}

0 comments on commit 0077bc9

Please sign in to comment.