#852
Peak Index in a Mountain Array
MediumArrayBinary SearchBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
We can leverage the properties of a mountain array using binary search. Since the array first increases and then decreases, we can eliminate half of the search space based on the relationship between the middle element and its neighbors.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers, left = 0 and right = n - 1.
- 2Step 2: While left < right, calculate mid = (left + right) // 2.
- 3Step 3: If arr[mid] < arr[mid + 1], it means the peak is on the right side, so set left = mid + 1.
- 4Step 4: Otherwise, the peak is on the left side or at mid, so set right = mid.
- 5Step 5: When left equals right, return left (or right) as the peak index.
solution.py11 lines
1# Full working Python code
2
3def peakIndexInMountainArray(arr):
4 left, right = 0, len(arr) - 1
5 while left < right:
6 mid = (left + right) // 2
7 if arr[mid] < arr[mid + 1]:
8 left = mid + 1
9 else:
10 right = mid
11 return leftℹ
Complexity note: This complexity is achieved because we are halving the search space with each iteration, characteristic of binary search.
- 1The peak element is always greater than its neighbors in a mountain array.
- 2Binary search is effective for problems with a sorted or partially sorted structure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.