Valid Mountain Array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array A of integers; we have to check whether it is a valid mountain array or not. We know that A is a mountain array if and only if it satisfies the following situations − size of A >= 3

There exists some index i in A such that −

  • A[0] < A[1] < ... A[i-1] < A[i]
  • A[i] > A[i+1] > ... > A[A.length - 1]

So, if the input is like [0,3,2,1], then the output will be True.

To solve this, we will follow these steps −

  • if size of A < 3, then
    • return False
  • i := 1
  • while i < size of A and A[i] > A[i-1], do
    • i := i + 1
  • if i is same as 1 or i is same as size of A , then
    • return False
  • while i < size of A and A[i] < A[i-1], do
    • i := i + 1
  • return true when i is same as size of A

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def validMountainArray(self, A):
      if(len(A)<3):
         return False
         i = 1
      while(i<len(A) and A[i]>A[i-1]):
         i+=1
      if(i==1 or i==len(A)):
         return False
      while(i<len(A) and A[i]<A[i-1]):
         i+=1
      return i==len(A)
ob = Solution()
print(ob.validMountainArray([0,3,2,1]))

Input

[0,3,2,1]

Output

True
raja
Published on 06-Jul-2020 09:10:25
Advertisements