Find in Mountain Array

HardBinary Search · Peak Finding🧩 Binary SearchLeetCode #1095 ↗Updated

Problem

A mountain array strictly increases up to a single peak and then strictly decreases (length ≥ 3, peak not at either end). You cannot see the array directly: it is hidden behind a MountainArray interface offering only get(i) and length(). Return the smallest index whose value equals target, or -1. Solutions making more than 100 get calls are rejected.
Inputarray = [1,2,3,4,5,3,1], target = 3Output2 (3 also at index 5; 2 is smaller)
Inputarray = [0,1,2,4,2,1], target = 3Output-1
Inputarray = [1,5,2], target = 2Output2

3 ≤ length ≤ 104  ·  0 ≤ target, values ≤ 109  ·  at most 100 calls to get

Try it yourself

Java
class Solution {
    public int findInMountainArray(int target, MountainArray mountainArr) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A mountain is two sorted arrays glued at the peak. Find the peak with binary search (compare get(mid) with get(mid+1)), then binary search the ascending side first — any hit there has a smaller index — and only then the descending side with the comparison flipped.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceLinear Scan Through get()

Time O(n)Space O(1)

Read indices from left to right and return the first one whose value equals target. Scanning in increasing order automatically yields the smallest matching index.

Java
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; // first hit = smallest index
    }
    return -1;
}

Correct, but needs up to 104 get calls — far over the 100-call cap.

At a glance

LevelApproachTimeSpace
Brute ForceLinear Scan Through get()O(n)O(1)
BetterClimb to the Peak, then Two Binary SearchesO(n)O(1)
OptimalThree Binary Searches (Peak, Left, Right)O(log n)O(1)
Common pitfalls
  • Searching the descending half first and returning the larger of two matching indices.
  • Reusing the ascending comparison on the right half — the direction must flip.
  • Calling get(mid) repeatedly instead of storing it, wasting the call budget.
Interview tips
  • Count the calls out loud: about 2·log n for the peak plus log n per side.
  • Write one search helper with a direction flag instead of two near-copies.
  • Note that caching values in a map is a cheap safety net if calls are very tight.
Pattern
Binary search on a bitonic array → find the turning point first, then search each monotone half.
My notes saved in this browser