15% off all plans & roadmaps Use code
See plansFind in Mountain Array
- LeetCode 1095
- Hard
- Binary Search Patterns
- Find Min/Max in Rotated Sorted Array
Updated
TL;DR: Find the smallest index of a target in a mountain array while calling get at most 100 times. Binary search for the peak first, then binary search the left slope before the right slope.
Problem
This is an interactive problem. You cannot read the array directly. You only access it through a MountainArray interface, where get(k) returns the value at index k and length() returns the size.
An array is a mountain array when its length is at least 3 and some index i, with 0 < i < length - 1, meets two rules. Values strictly increase from index 0 up to index i. Values strictly decrease from index i to the last index.
Given a mountain array, return the minimum index where the value equals target. If no index holds target, return -1.
Submissions that make more than 100 calls to MountainArray.get get Wrong Answer. Solutions that try to get around the judge are disqualified.
Example 1
Input: mountainArr = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 appears at indices 2 and 5. The minimum index is 2.
Example 2
Input: mountainArr = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 is not in the array, so the answer is -1.
Constraints
3 <= mountainArr.length() <= 10^40 <= target <= 10^90 <= mountainArr.get(index) <= 10^9
Constraints that matter
- The cap of 100 calls with n up to 10^4 rules out any linear scan, which can make up to 10^4 calls.
- Each call to get is the expensive step, so the algorithm must decide which half to discard from only a few reads per step.
- Length at least 3 guarantees a peak strictly inside the array, so comparing get(mid) with get(mid + 1) is always valid.
- Sorting is ruled out. Reading every value to sort it costs n calls, and sorting also loses the original indices.
- Values up to 10^9 fit in a 32-bit signed integer, so the comparisons need no wider type.
Hints
Hint 1
The array is not sorted, but it is sorted in two pieces.
Hint 2
Start at index 0 and call get on each index in order.
Solution
Intuition
The array is not sorted, but it is sorted in two pieces. Everything left of the peak climbs, and everything right of the peak falls. This shape is called a bitonic sequence, and binary search still works on it once you locate the peak.
Picture two sorted shelves of books set back to back, with the tallest book sitting at the joint. The joint is the peak index, and each shelf is an ordinary sorted run that gets searched with normal halving.
The limit of 100 calls, with n up to 10^4, forces you to cut the range in half at each step. A binary search on the index needs a yes or no decision at each midpoint. Comparing get(mid) with get(mid + 1) gives that decision. If the value rises, the peak lies to the right. If it falls, the peak is at mid or to the left.
Once the peak index is known, each slope is a plain sorted run. The left slope is ascending, so ordinary binary search applies. The right slope is descending, so the comparison flips.
Search the left slope first. Every left index is smaller than every right index, so this returns the smallest index when the target appears on both slopes.
Worked example
Input: mountainArr = [0, 1, 2, 4, 2, 1], target = 3 Output: -1 Explanation: The value 3 never appears. The linear scan finds no match, and the binary searches find no match on either slope, so the answer is -1.
Approach 1: Brute force: linear scan
Start at index 0 and call get on each index in order. Return the first index whose value equals target. Because you scan from left to right, the first match is the smallest index. This is correct and needs no structure.
It costs one call per element. With n up to 10^4, that is up to 10^4 calls, far above the limit of 100. The scan reads every value, even though the mountain shape lets you skip most of them.
Steps
- Read n = mountainArr.length().
- For i from 0 to n - 1, call mountainArr.get(i).
- If the value equals target, return i. The scan order makes this the smallest matching index.
- After the loop ends without a match, return -1.
Dry run
Scan [0, 1, 2, 4, 2, 1] for target 3.
- get(0) = 0, not 3.
- get(1) = 1, not 3.
- get(2) = 2, not 3.
- get(3) = 4, not 3.
- get(4) = 2, not 3.
- get(5) = 1, not 3.
The scan ends with no match, so the output is -1. This used 6 calls. The same scan on 10^4 elements uses 10^4 calls.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The loop runs at most n times, and each pass makes one get call and one comparison. Total work is O(n) calls, which exceeds the limit of 100 for large inputs. The algorithm stores only the loop index and n, so space is O(1).
PythonTested in our runner
class Solution:
def findInMountainArray(self, target: int, mountainArr: MountainArray) -> int:
n = mountainArr.length()
for i in range(n):
if mountainArr.get(i) == target:
return i
return -1JavaTested in our runner
class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
int n = mountainArr.length();
for (int i = 0; i < n; i++) {
if (mountainArr.get(i) == target) {
return i;
}
}
return -1;
}
}C++Tested in our runner
class Solution {
public:
int findInMountainArray(int target, MountainArray& mountainArr) {
int n = mountainArr.length();
for (int i = 0; i < n; i++) {
if (mountainArr.get(i) == target) {
return i;
}
}
return -1;
}
};JavaScriptTested in our runner
var findInMountainArray = function(target, mountainArr) {
const n = mountainArr.length();
for (let i = 0; i < n; i++) {
if (mountainArr.get(i) === target) {
return i;
}
}
return -1;
};GoTested in our runner
func findInMountainArray(target int, mountainArr *MountainArray) int {
n := mountainArr.length()
for i := 0; i < n; i++ {
if mountainArr.get(i) == target {
return i
}
}
return -1
}C#Tested in our runner
public class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
int n = mountainArr.length();
for (int i = 0; i < n; i++) {
if (mountainArr.get(i) == target) {
return i;
}
}
return -1;
}
}The Find Min/Max in Rotated Sorted Array infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Find Min/Max in Rotated Sorted Array
Part of Binary Search Patterns
Approach 2: Find the peak, then two binary searchesOptimalFind Min/Max in Rotated Sorted Array
What's slow: the linear scan reads elements that cannot change the answer. The insight that fixes it: the mountain shape lets you discard half the range at each probe. Comparing get(mid) with get(mid + 1) tells you which side holds the peak, so the peak takes about log n probes.
After the peak is known, search [0, peak] for the target with ascending comparisons. Search [peak + 1, n - 1] only if that fails, using descending comparisons. Searching the left side first gives the minimum index.
Why it is correct. The peak search keeps the invariant that the peak index always lies inside [low, high]. If get(mid) < get(mid + 1), mid is on the rising side, so the peak sits after mid and nothing at or before mid is lost. Otherwise mid is on the falling side or is the peak itself, so setting high = mid keeps the peak inside the range.
Steps
- Set low = 0 and high = n - 1.
- While low < high, set mid = (low + high) / 2 and compare get(mid) with get(mid + 1).
- If get(mid) < get(mid + 1), set low = mid + 1. Otherwise set high = mid.
- When the loop ends, low is the peak index.
- Binary search [0, peak]. On a match, return the index. If the value is below target, move right. Otherwise move left.
- Binary search [peak + 1, n - 1]. On a match, return the index. If the value is above target, move right. Otherwise move left.
- If both searches fail, return -1.
Dry run
Trace on [0, 1, 2, 4, 2, 1] with target 3. The table lists the changing state for each step.
| Phase | low | high | mid | get(mid) | get(mid + 1) | Decision |
|---|---|---|---|---|---|---|
| Peak 1 | 0 | 5 | 2 | 2 | 4 | 2 < 4, rising, set low = 3 |
| Peak 2 | 3 | 5 | 4 | 2 | 1 | 2 > 1, falling, set high = 4 |
| Peak 3 | 3 | 4 | 3 | 4 | 2 | 4 > 2, falling, set high = 3 |
| Peak done | 3 | 3 | - | - | - | low == high, peak = 3 (value 4) |
| Left 1 | 0 | 3 | 1 | 1 | - | 1 < 3, set low = 2 |
| Left 2 | 2 | 3 | 2 | 2 | - | 2 < 3, set low = 3 |
| Left 3 | 3 | 3 | 3 | 4 | - | 4 > 3, set high = 2 |
| Left done | 3 | 2 | - | - | - | low > high, no match |
| Right 1 | 4 | 5 | 4 | 2 | - | 2 < 3, descending, set high = 3 |
| Right done | 4 | 3 | - | - | - | low > high, no match, return -1 |
The trace makes 10 calls to get and ends with output -1.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the array length. Each loop halves its range, so the peak loop runs at most about log2 n times with two get calls per pass. Each target search also halves its range with one get call per pass. Total time is O(log n), and for n = 10^4 the worst case is about 56 calls, which is under the limit. The code keeps only a few integers, so space is O(1).
PythonTested in our runner
class Solution:
def findInMountainArray(self, target: int, mountainArr: MountainArray) -> int:
n = mountainArr.length()
# Phase 1: find the peak index
low, high = 0, n - 1
while low < high:
mid = (low + high) // 2
if mountainArr.get(mid) < mountainArr.get(mid + 1):
low = mid + 1 # still rising, peak is to the right
else:
high = mid # falling or at peak, peak is mid or left
peak = low
# Phase 2: ascending part [0, peak], searched first for the minimum index
low, high = 0, peak
while low <= high:
mid = (low + high) // 2
val = mountainArr.get(mid)
if val == target:
return mid
if val < target:
low = mid + 1
else:
high = mid - 1
# Phase 3: descending part [peak + 1, n - 1]
low, high = peak + 1, n - 1
while low <= high:
mid = (low + high) // 2
val = mountainArr.get(mid)
if val == target:
return mid
if val > target:
low = mid + 1 # values shrink to the right, so go right
else:
high = mid - 1
return -1JavaTested in our runner
class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
int n = mountainArr.length();
// Phase 1: find the peak index
int low = 0;
int high = n - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1; // still rising, peak is to the right
} else {
high = mid; // falling or at peak, peak is mid or left
}
}
int peak = low;
// Phase 2: ascending part [0, peak], searched first for the minimum index
low = 0;
high = peak;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Phase 3: descending part [peak + 1, n - 1]
low = peak + 1;
high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val > target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}C++Tested in our runner
class Solution {
public:
int findInMountainArray(int target, MountainArray& mountainArr) {
int n = mountainArr.length();
// Phase 1: find the peak index
int low = 0;
int high = n - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1; // still rising, peak is to the right
} else {
high = mid; // falling or at peak, peak is mid or left
}
}
int peak = low;
// Phase 2: ascending part [0, peak], searched first for the minimum index
low = 0;
high = peak;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Phase 3: descending part [peak + 1, n - 1]
low = peak + 1;
high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val > target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
};JavaScriptTested in our runner
var findInMountainArray = function(target, mountainArr) {
const n = mountainArr.length();
// Phase 1: find the peak index
let low = 0;
let high = n - 1;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1; // still rising, peak is to the right
} else {
high = mid; // falling or at peak, peak is mid or left
}
}
const peak = low;
// Phase 2: ascending part [0, peak], searched first for the minimum index
low = 0;
high = peak;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const val = mountainArr.get(mid);
if (val === target) {
return mid;
}
if (val < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Phase 3: descending part [peak + 1, n - 1]
low = peak + 1;
high = n - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const val = mountainArr.get(mid);
if (val === target) {
return mid;
}
if (val > target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
};GoTested in our runner
func findInMountainArray(target int, mountainArr *MountainArray) int {
n := mountainArr.length()
// Phase 1: find the peak index
low, high := 0, n-1
for low < high {
mid := low + (high-low)/2
if mountainArr.get(mid) < mountainArr.get(mid+1) {
low = mid + 1 // still rising, peak is to the right
} else {
high = mid // falling or at peak, peak is mid or left
}
}
peak := low
// Phase 2: ascending part [0, peak], searched first for the minimum index
low, high = 0, peak
for low <= high {
mid := low + (high-low)/2
val := mountainArr.get(mid)
if val == target {
return mid
}
if val < target {
low = mid + 1
} else {
high = mid - 1
}
}
// Phase 3: descending part [peak + 1, n - 1]
low, high = peak+1, n-1
for low <= high {
mid := low + (high-low)/2
val := mountainArr.get(mid)
if val == target {
return mid
}
if val > target {
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}C#Tested in our runner
public class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
int n = mountainArr.length();
// Phase 1: find the peak index
int low = 0;
int high = n - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (mountainArr.get(mid) < mountainArr.get(mid + 1)) {
low = mid + 1; // still rising, peak is to the right
} else {
high = mid; // falling or at peak, peak is mid or left
}
}
int peak = low;
// Phase 2: ascending part [0, peak], searched first for the minimum index
low = 0;
high = peak;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Phase 3: descending part [peak + 1, n - 1]
low = peak + 1;
high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int val = mountainArr.get(mid);
if (val == target) {
return mid;
}
if (val > target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}Common mistakes
- Writing
low = midinstead oflow = mid + 1when the slope is rising. When low and high are adjacent, mid equals low and the loop never ends. Move low past mid on a rising step. - Writing
high = mid - 1in the peak loop. On a falling step, mid can itself be the peak, so keep it withhigh = mid. - Searching the right slope before the left slope. Right-side indices are larger, so returning a right-side hit can skip a smaller left-side match. Search the left slope first and return its first hit.
- Using the ascending comparison on the right slope. The values there shrink as the index grows, so
if val < target: low = mid + 1walks away from the target. Flip the direction for the descending search. - Calling
get(mid)several times inside one loop body. Each call counts toward the 100 call limit, so store the value in a local variable and reuse it. - Setting
high = nin the peak search, or readingget(mid + 1)when mid is the last index. Keep high at n - 1 so mid + 1 always stays in range.
Edge cases
- Length 3, [1, 2, 1], target 2: the peak is index 1, so the answer is 1. Target 1 returns 0, because the left search runs first.
- Target equal to the peak value: the left search covers [0, peak] and returns the peak index, so the right search never runs.
- Target on both slopes, [1, 3, 5, 3, 1], target 3: the answer is 1, the left match, not 3.
- Target at index 0 or at the last index: a target of 0 at index 0 returns 0, and a match on the right slope at the last index returns n - 1.
- Target smaller than every value or larger than the peak: no search finds a match, so the answer is -1.
- Maximum size, n = 10^4 with the peak near the middle: the peak takes about 14 probes, and the whole run stays under 60 calls.
Follow-ups interviewers ask
- What if you need the largest index instead of the smallest?
- Search the right slope first, since its indices are all larger than the left slope's. Return the first match there. If the right search finds nothing, search the left slope and return its first match. Only the order of the two searches changes.
- What if the input is not guaranteed to be a mountain?
- Then the peak search can point the wrong way, and binary search has no reliable direction. You would need a linear scan, which breaks the call limit for large inputs. The mountain shape is what makes O(log n) possible.
- Can you reduce the number of get calls?
- Yes. Store each value in a local variable so the same index is never fetched twice in one step. This trims the constant factor, but the bound stays O(log n).
Find in Mountain Array FAQ
What is the time complexity of Find in Mountain Array?
The optimal solution runs in O(log n) time and uses O(1) extra space. It makes at most about 4 log2 n calls to get, which is roughly 56 when n is 10^4.
Why use binary search for Find in Mountain Array?
The mountain splits into an ascending run and a descending run, and each run is monotonic. Binary search finds the peak by comparing neighbours, then searches each run by comparing against the target. The limit of 100 calls rules out a linear scan.
Can Find in Mountain Array be solved in O(1) extra space?
Yes. The iterative version keeps only low, high, mid and peak, and it needs no recursion stack. A recursive version would use O(log n) stack space, so the loops are the better choice.
Why search the left side before the right side?
Every index on the left slope is smaller than every index on the right slope. So a match on the left is the minimum index, and returning it needs no extra check.
Why not sort the array first?
Sorting needs every value, so you would call get n times, which breaks the 100 call limit. Sorting also loses the original indices, which the answer must return.
Does a target equal to the peak value cause a problem?
No. The left search covers [0, peak], which includes the peak. The peak is found as a match there, and the right search never runs.
Asked at
See which companies ask this — Pro
Related problems
- Search in Rotated Sorted Array · same technique: Find Min/Max in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array · same technique: Find Min/Max in Rotated Sorted Array
- Search in Rotated Sorted Array II · same technique: Find Min/Max in Rotated Sorted Array
- Find Peak Element · same technique: Find Min/Max in Rotated Sorted Array
- Peak Index in a Mountain Array · same technique: Find Min/Max in Rotated Sorted Array
- Median of Two Sorted Arrays · same pattern: Binary Search Patterns
- Split Array Largest Sum · same pattern: Binary Search Patterns
- Find K-th Smallest Pair Distance · same pattern: Binary Search Patterns
- Minimize Max Distance to Gas Station · same pattern: Binary Search Patterns
- Koko Eating Bananas · same pattern: Binary Search Patterns