LeetCode Problem - Link


Problem

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if


Ex:

Input: arr = [2,1]
Output: false


Sequential Approach

Not much to explain, pretty self-explanatory - left some comments in the code to explain each step

/**
 * @param {number[]} arr
 * @return {boolean}
 */
var validMountainArray = function (arr) {
    var mode = arr[1] > arr[0] ? "ascending" : "descending"


    // early return
    if (mode == "descending") {
        return false
    }


    for (var i = 0; i < arr.length; i++) {
        // check equal siblings
        if (arr[i + 1] == arr[i]) {
            return false
        }


        if (mode == "ascending") {
            if (arr[i + 1] < arr[i]) {
                // started descending, exit this section
                mode = "descending"
            }
        }



        if (mode == "descending") {
            if (arr[i + 1] > arr[i]) {
                // failed, its increasing while descending, return false
                return false
            }
        }
    }


    // if loop ended and the mode is still ascending, there is no descent
    // which is a failed case
    if (mode == "ascending") {
        return false
    }


    return true
};