#1095
Find in Mountain Array
HardArrayBinary SearchInteractiveBinary SearchDivide and Conquer
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)
The optimal solution leverages the properties of the mountain array to efficiently locate the target using binary search. First, we find the peak of the mountain, then search both sides of the peak for the target.
⚙️
Algorithm
4 steps- 1Step 1: Use binary search to find the peak index of the mountain array.
- 2Step 2: Perform binary search on the left side of the peak to find the target.
- 3Step 3: If not found, perform binary search on the right side of the peak.
- 4Step 4: Return the minimum index if found, otherwise return -1.
solution.py37 lines
1# Full working Python code
2class MountainArray:
3 def __init__(self, arr):
4 self.arr = arr
5 def get(self, index):
6 return self.arr[index]
7 def length(self):
8 return len(self.arr)
9
10def findPeak(mountainArr):
11 left, right = 0, mountainArr.length() - 1
12 while left < right:
13 mid = (left + right) // 2
14 if mountainArr.get(mid) < mountainArr.get(mid + 1):
15 left = mid + 1
16 else:
17 right = mid
18 return left
19
20def binarySearch(mountainArr, target, left, right, ascending):
21 while left <= right:
22 mid = (left + right) // 2
23 mid_val = mountainArr.get(mid)
24 if mid_val == target:
25 return mid
26 if (mid_val < target) == ascending:
27 left = mid + 1
28 else:
29 right = mid - 1
30 return -1
31
32def findInMountainArray(target, mountainArr):
33 peak = findPeak(mountainArr)
34 index = binarySearch(mountainArr, target, 0, peak, True)
35 if index != -1:
36 return index
37 return binarySearch(mountainArr, target, peak + 1, mountainArr.length() - 1, False)ℹ
Complexity note: The time complexity is O(log n) due to the binary search for the peak and the subsequent searches, while the space complexity is O(1) since we are using a constant amount of extra space.
- 1Understanding the mountain array structure helps in optimizing the search process.
- 2Finding the peak is crucial as it divides the array into two sorted halves.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.