Monotonic Array

The given array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[ i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

Problem

Given an array of integers, write a function to determine whether the array is monotonic.
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j].  An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// We can solve this problem by iterating through the array and checking if the current element is greater than or less than the previous element.
// If the current element is greater than the previous element, we know that the array is monotone increasing.
// If the current element is less than the previous element, we know that the array is monotone decreasing.
// If the current element is equal to the previous element, we can ignore it.
// If we reach the end of the array and we have not returned false, we know that the array is monotonic.
// This solution is optimal because we only iterate through the array once.

function isMonotonic(array) {
  let direction = null;
  for (let i = 1; i < array.length; i++) {
    if (array[i] > array[i - 1]) {
      if (direction === 'decreasing') return false;
      direction = 'increasing';
    } else if (array[i] < array[i - 1]) {
      if (direction === 'increasing') return false;
      direction = 'decreasing'; }
  }
  return true;
}

// Do not edit the line below.
exports.isMonotonic = isMonotonic;

A.I. Evaluation of the Solution

The candidate's solution is correct and solves the problem. The candidate's approach is also optimal, as they only iterate through the array once.

Evaluated at: 2022-11-18 23:28:35