The Longest Mountain in Array coding problem gives you an integer array and asks you to find the length of the longest subarray that resembles a "mountain". A mountain subarray must have at least 3 elements. It must strictly increase to a peak element, and then strictly decrease. For example, [1, 4, 7, 3, 2] is a mountain, while [1, 2, 3] and [5, 4, 3] are not because they lack a descending or ascending part.
This array problem evaluates a candidate's ability to identify local extrema (peaks and valleys) and expand outwards. It is favored by interviewers because it has a highly intuitive solution that requires no extra space (), testing whether a candidate can avoid overcomplicating things with DP arrays or messy nested loops.
The best approach relies on the Two Pointers (Expand from Center) pattern, combined with peak finding. You iterate through the array from index 1 to N-2 to find potential "peaks" (an element where arr[i-1] < arr[i] > arr[i+1]). Once a peak is found, you use a left pointer to walk down the left slope and a right pointer to walk down the right slope. The length of the mountain is right - left + 1.
Let the array be [2, 1, 4, 7, 3, 2, 5].
We iterate looking for a peak:
1): Not a peak.4): Not a peak (smaller than 7).7): arr[2] < arr[3] > arr[4] (). This is a peak!
Now we expand outwards from index 3:4 -> 1. Stops at index 1.3 -> 2. Stops at index 5.
The mountain boundaries are index 1 to index 5. Length is 5 - 1 + 1 = 5. The mountain is [1, 4, 7, 3, 2].
We then resume searching for peaks starting from the right pointer's stopping point.A frequent mistake is failing to enforce the strict "mountain" shape constraint—specifically, counting flat plateaus (e.g., [1, 2, 2, 1]). The problem requires strict increases and decreases. Another mistake is using Dynamic Programming to track left-increasing and right-increasing lengths in two separate arrays. While this works, it uses extra space, whereas the expand-from-peak method gracefully achieves space.
For the Longest Mountain in Array interview pattern, practice the "expand from center" technique. It is the exact same logic used in finding Longest Palindromic Substrings. By identifying the core feature of the target (in this case, the peak) and exploring outward, you drastically reduce the number of edge cases you have to handle compared to trying to track upward and downward states simultaneously from left to right.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Palindrome After Substring Concatenation I | Medium | Solve | |
| Find the Integer Added to Array II | Medium | Solve | |
| Get the Maximum Score | Hard | Solve | |
| Count the Number of Incremovable Subarrays I | Easy | Solve | |
| Number of Arithmetic Triplets | Easy | Solve |