941. Valid Mountain Array LeetCode Solution

In this guide, you will get 941. Valid Mountain Array LeetCode Solution with the best time and space complexity. The solution to Valid Mountain Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Valid Mountain Array solution in C++
  4. Valid Mountain Array solution in Java
  5. Valid Mountain Array solution in Python
  6. Additional Resources
941. Valid Mountain Array LeetCode Solution image

Problem Statement of 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 + 1] > … > arr[arr.length – 1]

Example 1:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true

Constraints:

1 <= arr.length <= 104
0 <= arr[i] <= 104

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

941. Valid Mountain Array LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

941. Valid Mountain Array LeetCode Solution in Java

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;
  }
}
// code provided by PROGIEZ

941. Valid Mountain Array LeetCode Solution in Python

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
# code by PROGIEZ

Additional Resources

See also  763. Partition Labels LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.