DSA problem
Find in Mountain Array
You may recall that an array arr is a mountain array if and only if: arr.length >= 3 and there exists some i with 0 < i < arr.length - 1 such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]. Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.
You cannot access the mountain array directly. You can only access the array using a MountainArray interface: MountainArr.get(k) returns the element of the array at index k (0-indexed), and MountainArr.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
Solve this in three binary searches:
- Locate the peak with the slope-comparison technique from "Find Peak Element". Compare
arr[mid]andarr[mid + 1]; rising means the peak is to the right, falling means it is at or beforemid. This findspeakin O(log n) calls. - Run an ascending binary search on
[0, peak]fortarget. If found, return the index immediately (it's the smallest by definition). - Otherwise, run a descending binary search on
[peak + 1, n - 1]fortarget. Same template but the comparison is inverted.
Total calls to get: roughly 3 log n, comfortably within 100 for n <= 10^4. Memoize results in a local map if you want to be extra defensive, though it is not strictly required. The complexity is O(log n) calls, O(1) memory.
Examples
array = [1,2,3,4,5,3,1], target = 32array = [0,1,2,4,2,1], target = 3-1array = [1,5,2], target = 22Constraints
- 3 <= mountain_arr.length() <= 10^4
- 0 <= target <= 10^9
- 0 <= mountain_arr.get(index) <= 10^9
- Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.