562. Valid Mountain Array
An integer array is a mountain when it rises and then falls — precisely:
- it contains at least 3 elements, and
- there is a peak position
i(never the first or last index) such that the values strictly increase from the start up toarr[i]and then strictly decrease fromarr[i]to the end.
Strictly means strictly: a flat step (two equal neighbors) breaks the mountain, and so does an array that only climbs or only falls.
Your function receives the array arr and returns true if it is a mountain, false otherwise.
Example 1:
Input: arr = [0, 2, 3, 4, 5, 2, 1, 0]
Output: true
Explanation: Values climb strictly from 0 up to the peak 5 at index 4, then fall strictly back down to 0.
Example 2:
Input: arr = [3, 5, 5]
Output: false
Explanation: The step from 5 to 5 is flat — the descent must be strict, so this is not a mountain.
Example 3:
Input: arr = [0, 1, 2, 3]
Output: false
Explanation: The array only ever climbs. A mountain needs a strict descent after the peak, and the peak cannot be the last element.
Constraints:
- 1 ≤ arr.length ≤ 10⁴
- 0 ≤ arr[i] ≤ 10⁶
Hints:
Picture one hiker: they must walk uphill at least one step, turn around exactly once, and walk downhill to the very end. What are all the ways that trip can fail?
Walk a pointer forward while the values strictly increase. Where it stops is the only possible peak — check it isn't the first or last index, then keep walking while values strictly decrease.
The array is a mountain exactly when that second walk ends at the last index.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: arr = [0, 2, 3, 4, 5, 2, 1, 0]
Expected output: true