Valid Mountain Array
To solve this problem, we can use two pointers, starting from both ends of the array, and see if they meet at some point. We move our pointers towards the center of the array until we find a sequence that is not in increasing order. If the two pointers meet at the same position and it’s not the first or the last element of the array, we know that it’s a valid mountain array.
Here is the Python code:
|
|
In this code, we first check if the length of arr
is less than 3. If it is, we return False
because a valid mountain array needs at least 3 elements. We then initiate two pointers, left
and right
, to the start and the end of the arr
, respectively. We move the left
pointer to the right as long as the current element is less than the next one, and move the right
pointer to the left as long as the current element is less than the previous one.
Finally, we check if the left
pointer is equal to the right
pointer, which indicates that we have a peak in the array, and if this peak is not the first or the last element of the array. If these conditions are met, we return True
, else we return False
.
Two people climb from left and from right separately. If they are climbing the same mountain, they will meet at the same point.