Advertisement
DeepRest

Valid Mountain Array

Jan 24th, 2022 (edited)
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. '''
  2. Checks:
  3. 1. The whole array can neither be strictly increasing or strictly decreasing entirely.
  4. 2. The strictly decreasing part should come after the strictly increasing part and together they should make up the entire array
  5. '''
  6. #1. One Pointer
  7. class Solution:
  8.     def validMountainArray(self, arr: List[int]) -> bool:
  9.         i, n = 0, len(arr)
  10.         while i<n-1 and arr[i]<arr[i+1]:
  11.             i += 1
  12.         if i==0 or i==n-1:
  13.             return False
  14.         while i<n-1 and arr[i]>arr[i+1]:
  15.             i += 1
  16.         return i==n-1
  17.  
  18. #2. Two pointer
  19. #credits to lee215 solution for idea
  20. class Solution:
  21.     def validMountainArray(self, arr: List[int]) -> bool:
  22.         n = len(arr)
  23.         i, j = 0, n-1
  24.         while i<n-1 and arr[i]<arr[i+1]:
  25.             i += 1
  26.         while j>0 and arr[j]<arr[j-1]:
  27.             j -= 1  
  28.         return i == j and 0 < i < n-1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement