mountain array

Valid Mountain Array Solution in JavaScript

Harsh Vats on August 05, 2021

There's a very good problem on leetcode, about valid mountain array.

The steps to tackle it should be:

  1. If length of array is less than 3, then return false.
  2. If the array never started increasing, then return false.
  3. Then initialize a variable called maxFound to false and run a for loop till arr.length - 2 (because we will try to access arr[i++] and we don't want to go beyond array length).
  4. If element is equal to next element, return false.
  5. If the next element is greater than current element, set maxFound to true.
  6. If max is found and still the next element is greater than current, then return false.
  7. Now that you are out of for loop, if max is not found, that means array never started decreasing, then return false, otherwise return true.

Here's the solution of that problem in javascript.

var validMountainArray = function (arr) {
if (arr.length < 3) return false
if (arr[1] < arr[0]) return false
let maxFound = false
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i + 1] === arr[i]) return false
if (maxFound && arr[i + 1] > arr[i]) return false
if (arr[i] > arr[i + 1]) {
maxFound = true
// return maxFound ? true : false
return maxFound
  • linkedin
  • facebook
  • twitter
Connect with me on LinkedIn
© 2021, Built by Harsh Vats