523/670

523. Peak Index in a Mountain Array

Medium

An array is a mountain when it has at least 3 elements and climbs strictly upward to a single highest value, then falls strictly downward. That shape guarantees exactly one index whose value is larger than both of its neighbors.

You are given a mountain array arr. Return the 0-based index of its peak — the position of the largest element.

A left-to-right scan finds it easily; the real exercise is to answer in O(log n) time.

A mountain array and its peakExample 1: the values climb strictly to 10 and then fall strictly. The unique peak sits at index 2.
arr = [0, 2, 10, 7, 4, 1]0210741012345strictly up, then strictly down — peak at index 2

Example 1:

Input: arr = [0, 2, 10, 7, 4, 1]

Output: 2

Explanation: The values rise 0 → 2 → 10, then fall 10 → 7 → 4 → 1. The peak 10 sits at index 2.

Example 2:

Input: arr = [0, 1, 0]

Output: 1

Explanation: The smallest possible mountain: up once, down once. The peak is the middle element.

Constraints:

  • 3 ≤ arr.length ≤ 10⁵
  • 0 ≤ arr[i] ≤ 10⁶
  • arr is guaranteed to be a mountain: strictly increasing up to one peak, then strictly decreasing.

Hints:

The peak is the only place where the array stops rising: the first index i with arr[i] > arr[i+1]. A single pass finds it — but the follow-up asks for O(log n).

Compare arr[mid] with arr[mid + 1]. If arr[mid] < arr[mid + 1] you are standing on the rising slope, so the peak lies strictly to the right; otherwise the peak is at mid or somewhere to its left. That one comparison always discards half the range.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: arr = [0, 2, 10, 7, 4, 1]

Expected output: 2