sagelearnai

Find in Mountain Array

Difficulty: Hard · Pattern: Binary Search · LeetCode #1095

A mountain array strictly increases to a peak, then strictly decreases. You can only access it through mountainArr.get(i) and mountainArr.length(), with at most 100 calls to get. Return the minimum index where get(index) == target, or −1.

Examples

text
array = [1, 2, 3, 4, 5, 3, 1], target = 3  →  2    (also at 5; return the smaller)
array = [0, 1, 2, 4, 2, 1], target = 3     →  −1

Hints

  1. Three binary searches: find the peak, search the increasing left part, then the decreasing right part.

Approach

  1. Peak: binary search with get(mid) < get(mid+1) → go right.
  2. Search [0, peak] as an ascending array; if found, return it (that's the minimum index).
  3. Otherwise search [peak+1, n−1] as a descending array.

Each search makes O(log n) calls, roughly 3·log₂ n in total, which is well under 100 for n ≤ 10⁴.

Complexity

Time: O(log n) calls to get. Space: O(1).

Python solution
def findInMountainArray(target, mountainArr):
    n = mountainArr.length()
    lo, hi = 0, n - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if mountainArr.get(mid) < mountainArr.get(mid + 1): lo = mid + 1
        else: hi = mid
    peak = lo
    def bsearch(lo, hi, asc):
        while lo <= hi:
            mid = (lo + hi) // 2
            v = mountainArr.get(mid)
            if v == target:
                return mid
            if (v < target) == asc: lo = mid + 1
            else: hi = mid - 1
        return -1
    i = bsearch(0, peak, True)
    return i if i != -1 else bsearch(peak + 1, n - 1, False)
JavaScript solution
function findInMountainArray(target, mountainArr) {
  const n = mountainArr.length();
  let lo = 0, hi = n - 1;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (mountainArr.get(mid) < mountainArr.get(mid + 1)) lo = mid + 1; else hi = mid; }
  const peak = lo;
  const bs = (lo, hi, asc) => {
    while (lo <= hi) { const mid = (lo + hi) >> 1, v = mountainArr.get(mid); if (v === target) return mid; if ((v < target) === asc) lo = mid + 1; else hi = mid - 1; }
    return -1;
  };
  const i = bs(0, peak, true);
  return i !== -1 ? i : bs(peak + 1, n - 1, false);
}