6

Valid Mountain Array — Solution and Approch in Java

 3 years ago
source link: https://dev.to/rubleen1903/valid-mountain-array-solution-and-approch-in-java-p6g
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Valid Mountain Array — Solution and Approch in Java

Jul 31

・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

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 :

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 modeExit 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 !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK