SDE & MLE Prep

1095. Find in Mountain Array

Problem

A mountain array (strictly increasing, then strictly decreasing) is hidden behind an interface with get(index) and length(). Return the smallest index whose value equals target, or −1, using at most 100 get calls.

Example: array = [1,2,3,4,5,3,1], target = 3 → 2

Constraints: length ≤ 10⁴.

Only ~100 get calls are allowed, so three binary searches: (1) find the peak (first i with a[i] > a[i+1]), (2) search the ascending left part, (3) if not found, search the descending right part (comparison flipped). Checking the left side first returns the minimum index.

Complexity: O(log n) calls.

class Solution:
    def findInMountainArray(self, target: int, mountainArr: 'MountainArray') -> int:
        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 search(lo, hi, ascending):
            while lo <= hi:
                mid = (lo + hi) // 2
                v = mountainArr.get(mid)
                if v == target:
                    return mid
                if (v < target) == ascending:
                    lo = mid + 1
                else:
                    hi = mid - 1
            return -1

        i = search(0, peak, True)
        return i if i != -1 else search(peak + 1, n - 1, False)