Longest Mountain in Array - Problem
Mountain Array Explorer

Imagine you're a hiker exploring a landscape represented by an array of elevations. Your goal is to find the longest mountain in this terrain!

A mountain array has these characteristics:
• Must have at least 3 elements
• Has a strict upward slope: arr[0] < arr[1] < ... < arr[peak]
• Followed by a strict downward slope: arr[peak] > arr[peak+1] > ... > arr[end]

Given an array of integers representing elevations, return the length of the longest mountain subarray. If no valid mountain exists, return 0.

Example: In array [2,1,4,7,3,2,5], the mountain [1,4,7,3,2] has length 5.

Input & Output

example_1.py — Python
$ Input: [2,1,4,7,3,2,5]
Output: 5
💡 Note: The longest mountain is [1,4,7,3,2] with length 5. It goes up: 1→4→7, then down: 7→3→2.
example_2.py — Python
$ Input: [2,2,2]
Output: 0
💡 Note: No mountain exists because all elements are equal. A mountain requires strict increase then strict decrease.
example_3.py — Python
$ Input: [0,1,2,3,4,5,4,3,2,1,0]
Output: 11
💡 Note: The entire array forms one mountain: goes up 0→1→2→3→4→5, then down 5→4→3→2→1→0.

Visualization

Tap to expand
Mountain Trail Analysis147Peak32Longest Mountain: Length 5Algorithm StateUp count: 2 stepsDown count: 2 stepsMountain length: 5Key InsightTrack up/down lengthsMountain = up + down + 1Reset on flat sections
Understanding the Visualization
1
Scan the trail
Walk through elevation points one by one
2
Track ascent
Count consecutive upward steps
3
Track descent
Count consecutive downward steps after ascent
4
Measure mountain
When descent ends, calculate total mountain length
Key Takeaway
🎯 Key Insight: A mountain is uniquely defined by its upward and downward segment lengths. By tracking these lengths in one pass, we can efficiently find the longest mountain without checking all possible subarrays.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the array, examining each element once

n
2n
Linear Growth
Space Complexity
O(1)

Only using a few variables to track upward/downward lengths and maximum

n
2n
Linear Space

Constraints

  • 1 ≤ arr.length ≤ 104
  • 0 ≤ arr[i] ≤ 104
  • Mountain must have both upward and downward segments
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
42.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen