AAlgoLoopSpaced repetition for LeetCode
HARDBinary SearchLeetCode ↗

Find in Mountain Array

The key idea

A mountain array is two sorted runs glued at a peak: strictly increasing up to the peak, strictly decreasing after it. Find the peak with a binary search, then run a normal ascending binary search on the left side first — the smallest index wins, so only fall back to a descending binary search on the right side if the left search misses.

Problem

You are given a mountain array mountainArr and an integer target. Return the minimum index such that mountainArr.get(index) == target. If target is not in the array, return -1.

You cannot access the array directly. You may only ask for an element through the MountainArray interface: mountainArr.get(k) returns the element at index k and mountainArr.length() returns the array's length. A submission that calls get more than 100 times is judged wrong, so a linear scan will not pass — you must use the mountain shape to your advantage.

An array is a mountain if it strictly increases up to a single peak and then strictly decreases. Because both sides are sorted, the answer is reachable with a handful of binary searches instead of touching every element.

Constraints

Examples

Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2
Input: array = [0,1,2,4,2,1], target = 3 Output: -1

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems