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 i with 0 < i < arr.length - 1 such 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 index k (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
Find in Mountain Array: Limited API Calls12345310123456PeakTarget = 3Found at indices 2 and 5Step 1: Find peak using binary search (index 4)Step 2: Search ascending part [0,4] → found at index 2Step 3: Return minimum index (skip descending search)Output: 2 (minimum index)
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
Asked in
Google 45 Facebook 38 Amazon 32 Apple 25
125.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen