Valid Mountain Array: Walk Up, Walk Down, Check the Ends
The problem
An array is a mountain if it has at least three elements, strictly increases to a peak, then strictly decreases. The peak cannot be the first or last element. Return whether the array is a mountain.
The single scan
Climb while the next value is larger, make sure you actually climbed and did not reach the end, then descend and check that you finished. It is O(n) time and O(1) space.
Why the middle check matters
The test i == 0 or i == n - 1 rejects arrays that only go down (no climb) and arrays that only go up (no descent). Forgetting it is the most common wrong answer, because [1, 2, 3] would otherwise pass.
Equal neighbours
Strictness means any plateau, such as [0, 2, 2, 1], is not a mountain. Both loops use strict comparisons, so the scan stops at the plateau and the final check fails. Mention this explicitly.
Two-pointer variant
Start one pointer at each end and walk each one uphill toward the middle. The array is a mountain when both pointers stop at the same index and neither stayed at its starting end. It is the same complexity, and some interviewers enjoy it as a follow-up.
Related questions
- Peak Index in a Mountain Array, where binary search gives O(log n) because the array is guaranteed to be a mountain.
- Longest Mountain in Array, which extends the same climb-then-descend scan to track the best length.
Disclosure: I work on Linkjob AI. If you want structured practice for interviews like this, AI tool for job interviews can help you rehearse and get real-time hints.