Find in Mountain Array

Hard

Topics
ArrayBinary Search

An array is a mountain array if there is some index peak with 0 < peak < n - 1 such that nums[0] < ... < nums[peak] > ... > nums[n - 1].

Given a mountain array nums and a target, return the smallest index whose value equals the target, or -1 if the target is not present.

The original problem hides the array behind a MountainArray interface with a call budget. Here the array is passed directly, but the intended solution is the same three binary searches — do not scan linearly.

Example 1

1234531
The values rise to a peak at index 4 and then fall, so the array is two monotonic halves. Target 3 is at index 2 — and when it appears in both halves the smaller index wins.
Bars are the array values; the brace marks the ascending half.
Input:  nums = [1,2,3,4,5,3,1], target = 3
Output: 2
Explanation: The value 3 appears at indices 2 and 5; the smaller index is 2.

Example 2

012421
Target 3 is absent, so -1.
Input:  nums = [0,1,2,4,2,1], target = 3
Output: -1

Constraints

  • 3 <= nums.length <= 10^4
  • 0 <= target <= 10^9
  • 0 <= nums[i] <= 10^9
  • nums is a valid mountain array
Editorial — intuition, approach, complexity and pitfalls

Intuition

A mountain array is two monotone runs glued at the peak, and binary search needs monotonicity. So spend one binary search finding the peak, then run two more — one ascending on the left, one descending on the right. Search the left side first, because any hit there automatically has the smaller index and lets you return immediately.

Approach

  1. Find the peak with a binary search on the slope: if nums[mid] < nums[mid + 1] you are still climbing, so move lo to mid + 1; otherwise move hi to mid. They converge on the peak index.
  2. Binary search [0, peak] as a normal ascending array. If the target is found, return that index — it is necessarily the smallest.
  3. Otherwise binary search [peak + 1, n - 1] with the comparison inverted, since that half descends.
  4. Return -1 if neither search finds the target. Three O(log n) searches total.
class Solution:
    def findInMountainArray(self, nums, target):
        n = len(nums)
        lo, hi = 0, n - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < nums[mid + 1]:
                lo = mid + 1
            else:
                hi = mid
        peak = lo

        lo, hi = 0, peak
        while lo <= hi:
            mid = (lo + hi) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1

        lo, hi = peak + 1, n - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] > target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1

Dry Run

nums = [1, 2, 3, 4, 5, 3, 1], target = 3

Phase 1, find the peak. Compare each mid with its right neighbour:
  lo=0 hi=6   mid=3   4 < 5   still climbing, lo=4
  lo=4 hi=6   mid=5   3 > 1   past the peak, hi=5
  lo=4 hi=5   mid=4   5 > 3   past the peak, hi=4
  lo=hi=4     peak=4

Phase 2, ordinary ascending binary search over 0..4:
  lo=0 hi=4   mid=2   nums[2]=3 == target   return 2

answer 2

Phase 3 never runs here, and that ordering is deliberate: 3 also appears at
index 5 on the descending side, so searching the descending half first would
return 5. Ascending-first is what makes the answer the SMALLEST index.

Phase 1 needs no target at all. It is a binary search on the predicate "am I
still climbing", which is monotonic even though the array is not sorted --
which is the thing worth taking away from this problem.

Complexity

  • Time — O(log n) — three independent binary searches.
  • Space — O(1) — only index variables.

Common Pitfalls

  • Search the ascending half first. Finding the target on the descending side and returning it can miss a smaller index on the left.
  • The descending search flips the comparison. Reusing the ascending version on the right half silently returns -1.
  • The peak search compares nums[mid] to nums[mid + 1], so the loop must use lo < hi — lo <= hi reads past the end.
  • The peak itself belongs to the left search range. Excluding it misses a target sitting exactly on the summit.

Full Solution — all languages

class Solution:
    def findInMountainArray(self, nums, target):
        n = len(nums)
        lo, hi = 0, n - 1
        while lo < hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] < nums[mid + 1]:
                lo = mid + 1
            else:
                hi = mid
        peak = lo

        lo, hi = 0, peak
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1

        lo, hi = peak, n - 1
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] > target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
SensAI
Beta
Tap the mic to stop voice mode