Find in Mountain Array - Problem
You may recall that an array arr is a mountain array if and only if:
arr.length >= 3- There exists some
iwith0 < i < arr.length - 1such that:arr[0] < arr[1] < ... < arr[i - 1] < arr[i]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.
Important: You cannot access the mountain array directly. You may only access the array using a MountainArray interface:
MountainArray.get(k)returns the element of the array at indexk(0-indexed).MountainArray.length()returns the length of the array.
Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer.
Input & Output
Example 1 — Basic Mountain Search
$
Input:
mountain_arr = [1,2,3,4,5,3,1], target = 3
›
Output:
2
💡 Note:
The mountain array is [1,2,3,4,5,3,1] with peak at index 4 (value 5). Target 3 appears at indices 2 and 5, so return the minimum index 2.
Example 2 — Target Not Found
$
Input:
mountain_arr = [0,1,2,4,2,1], target = 3
›
Output:
-1
💡 Note:
The mountain array is [0,1,2,4,2,1] with peak at index 3 (value 4). Target 3 does not exist in the array, so return -1.
Example 3 — Target at Peak
$
Input:
mountain_arr = [1,2,0,1,0], target = 0
›
Output:
2
💡 Note:
The mountain array is [1,2,0,1,0] with peak at index 1 (value 2). Target 0 appears at indices 2 and 4, so return the minimum index 2.
Constraints
- 3 ≤ mountain_arr.length() ≤ 104
- 0 ≤ target ≤ 109
- mountain_arr is guaranteed to be a mountain array
Visualization
Tap to expand
Understanding the Visualization
1
Input
Mountain array [1,2,3,4,5,3,1] and target 3
2
Process
Find peak, then binary search left and right sides
3
Output
Return minimum index where target is found
Key Takeaway
🎯 Key Insight: A mountain array is just two sorted arrays joined at a peak - use binary search on each part separately
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code