LeetCode 941: Valid Mountain Array Solution

Master LeetCode problem 941 (Valid Mountain Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

941. Valid Mountain Array

Easy

Problem Explanation

Explanation

To determine if the given array is a valid mountain array, we need to find the peak element of the mountain. The peak element should be such that it is not the first or last element of the array. If the peak element is found, we can check if all elements to the left of the peak are in increasing order and all elements to the right of the peak are in decreasing order.

  • If any element to the right of the peak is greater than or equal to the peak element, or if we do not find a peak element, the array is not a valid mountain array.
  • If the conditions are satisfied, the array is a valid mountain array.

Time complexity: O(n) where n is the length of the input array. Space complexity: O(1)

Solution Code

class Solution {
    public boolean validMountainArray(int[] arr) {
        int n = arr.length;
        int i = 0;

        // Walk up
        while (i + 1 < n && arr[i] < arr[i + 1]) {
            i++;
        }

        // Peak can't be the first or last element
        if (i == 0 || i == n - 1) {
            return false;
        }

        // Walk down
        while (i + 1 < n && arr[i] > arr[i + 1]) {
            i++;
        }

        return i == n - 1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 941 (Valid Mountain Array)?

This page provides optimized solutions for LeetCode problem 941 (Valid Mountain Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 941 (Valid Mountain Array)?

The time complexity for LeetCode 941 (Valid Mountain Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 941 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 941 in Java, C++, or Python.

Back to LeetCode Solutions