Skip to content

Instantly share code, notes, and snippets.

@Josephchinedu
Created May 19, 2022 18:36
Show Gist options
  • Save Josephchinedu/bc33a495f05a191270ce928c4847c599 to your computer and use it in GitHub Desktop.
Save Josephchinedu/bc33a495f05a191270ce928c4847c599 to your computer and use it in GitHub Desktop.
Valid Mountain Array

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:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Steps:

  • Check if the the input of the arrray is less than 3. if so, return False
  • initialize an index that'll start from 1
  • we run a loop that will check for an increasing hill we do that by checking if the current element that we're on is bigger that the previous element. if that's the case, we'll just increment our index
  • when the loop is done running, we've to check for couple of cases
    • what is the index is equal to 1. that means the loop did nothing and it also mean that there's no increasing hill. then we return false
    • another case is, if the index move and if it move to the end of the array. that means there's no decreasing hill in our array, we return False
  • if the condition pass, then we need to run a loop to check for decreasing hill. we do so by checking if the current element is smaller than the element before it. if that's the case we increament our index
  • Now, we need to check the valid array, we do so by checking if index is equal to len of the array, if index is eqaul to len of array that means we've reach the end of the array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment