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);
}
}
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 !
Top comments (1)
A Mountain Array is a special sequence of numbers that first ascends to a peak and then descends, resembling a mountain's silhouette. Each element represents a step in this orderly climb or descent. In folklore, some believe that such formations hold hidden meanings, much like an amulet symbolizes protection or luck. Just as an amulet guards its wearer, the peak of a Mountain Array represents strength and balance, surrounded by harmonious slopes. Exploring these arrays can feel like deciphering a mystical talisman, where every number has its place, purpose, and significance, creating a structure both beautiful and mathematically intriguing.