0

I feel stupid for asking but why is this returning true when it should be false?

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.

var isMonotonic = function(A) {
    let ascendOrder = A.sort((a,b) => a - b);
    console.log(ascendOrder);
    let descendOrder = A.sort((a,b) => b - a);
    console.log(descendOrder);
    if (A !== ascendOrder && A !== descendOrder) {
        return false;
    } else {
        return true;
    }
}
console.log(isMonotonic([1, 3, 2])); // false
Ron Rance
  • 83
  • 1
  • 4
  • 1
    If you want to take that approach, you'll need to (1) clone the `A` before sorting so as not to mutate it (2) iterate through each index of the array to compare against the same index in the other array – CertainPerformance Apr 17 '21 at 20:10
  • As a hint... `isAscending = a => a.slice(1).every((e,i) => e > a[i])`. – Redu Apr 17 '21 at 20:17
  • The same problem is with Java as well, equals and == is not the same. – Anton Krug Apr 17 '21 at 20:19

0 Answers0