Skip to content

941. Valid Mountain Array 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  bool validMountainArray(vector<int>& arr) {
    if (arr.size() < 3)
      return false;

    int l = 0;
    int r = arr.size() - 1;

    while (l + 1 < arr.size() && arr[l] < arr[l + 1])
      ++l;
    while (r > 0 && arr[r] < arr[r - 1])
      --r;

    return l > 0 && r < arr.size() - 1 && l == r;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public boolean validMountainArray(int[] arr) {
    if (arr.length < 3)
      return false;

    int l = 0;
    int r = arr.length - 1;

    while (l + 1 < arr.length && arr[l] < arr[l + 1])
      ++l;
    while (r > 0 && arr[r] < arr[r - 1])
      --r;

    return l > 0 && r < arr.length - 1 && l == r;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def validMountainArray(self, arr: list[int]) -> bool:
    if len(arr) < 3:
      return False

    l = 0
    r = len(arr) - 1

    while l + 1 < len(arr) and arr[l] < arr[l + 1]:
      l += 1
    while r > 0 and arr[r] < arr[r - 1]:
      r -= 1

    return l > 0 and r < len(arr) - 1 and l == r