#941
Valid Mountain Array
EasyArrayTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass through the array to check for the mountain conditions, making it more efficient. We can track the increasing and decreasing phases with a simple loop.
⚙️
Algorithm
4 steps- 1Step 1: Check if the length of the array is less than 3; if so, return false.
- 2Step 2: Initialize two pointers: one for the increasing phase and one for the decreasing phase.
- 3Step 3: Move through the array to find the peak, ensuring the values are strictly increasing until the peak is found.
- 4Step 4: Continue moving through the array to ensure the values are strictly decreasing after the peak.
solution.py15 lines
1# Full working Python code
2
3def validMountainArray(arr):
4 n = len(arr)
5 if n < 3:
6 return False
7 i = 0
8 while i + 1 < n and arr[i] < arr[i + 1]:
9 i += 1
10 if i == 0 or i == n - 1:
11 return False
12 while i + 1 < n and arr[i] > arr[i + 1]:
13 i += 1
14 return i == n - 1
15ℹ
Complexity note: The complexity is O(n) because we only traverse the array once, checking for the increasing and decreasing conditions in a single pass.
- 1A valid mountain array must have a peak that is neither the first nor the last element.
- 2The array must strictly increase to the peak and strictly decrease after the peak.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.