DEV Community

loading...

Valid Mountain Array — Solution and Approch in Java

Rubleen Kaur
Looking for SDE profiles - Codes in C++,Java and also is a web developer
・2 min read

I have started practising for my interviews on Leetcode and thought of sharing each problem and the approach i use for solving them through these blogs.
The first problem I chose is Valid Mountain Array and is an easy problem as compared to the one’s i’ve come across on leetcode.Each and every problem has an algorithmic approach one needs to understand before moving ahead with coding the solution.

The problem we are going to discuss :

Valid Mountain Array

image

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]
*arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Approach :

image

I solved it using two variables which were used to check the given conditions.
Do go through the above images to get a detailed approach and alogirthm how the problem was solved.

Solution in Java !

// 941. Valid Mountain Array
// Easy
// 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]
// arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

//Solution in java

class Solution {
    public boolean validMountainArray(int[] arr) {
        int i = 0;
        int j = arr.length - 1;
        int n = arr.length - 1;
        while (i + 1 < n && arr[i] < arr[i+1]) {
            i++;
        }

        while (j > 0 && arr[j] < arr[j-1]) {
            j--;
        }

        return (i > 0 && i == j && j < n);
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope the solution was easy to understand !If you still have any doubts feel free to reach out to me at Linkedin! I am attaching my linkedin id below, connect or follow to support and asks your doubts there !
Happy Coding! 🐱‍💻
Connect and Follow on Linkedin and Github to show support !

Discussion (0)