Python coding

Peak of a mountain list

heights is shaped like a mountain: its values strictly rise to a single highest value and then strictly fall, as in [1, 4, 7, 5, 2]. Return the index of that highest value.

Constraints: len(heights) >= 3, and the peak is never the first or the last value. Aim for O(log n): scanning for the maximum reads every value.

  • peak_index([0,1,0]) → 1
  • peak_index([1,4,7,5,2]) → 2
  • peak_index([0,10,5,2]) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The list isn't sorted, but the answer to "is heights[i] < heights[i + 1]?" is: yes on the way up, no from the peak on. Binary search for the first no.

Hint 2

Compare heights[mid] with heights[mid + 1]. Still climbing: the peak is right of mid. Going down: the peak is mid or left of it, so keep mid in the range.

Solution and why it works
pythonO(log n) · O(1)
def peak_index(heights: list[int]) -> int:
    lo, hi = 0, len(heights) - 1         # the peak is somewhere in [lo, hi]
    while lo < hi:
        mid = (lo + hi) // 2             # mid < hi, so mid + 1 is a valid index
        if heights[mid] < heights[mid + 1]:
            lo = mid + 1                 # still climbing: the peak is to the right
        else:
            hi = mid                     # going down: the peak is mid or to its left
    return lo

Binary search needs a monotonic question, not a sorted list. "Is the next value higher?" is yes on the way up and no from the peak on, so the peak is the first no, and comparing mid with mid + 1 drops half the range each step: ~20 checks for a million values. Keep hi = mid, not mid - 1: when the slope goes down at mid, mid itself may be the peak.

Related lab: Loops in motion