CodingNodes / Binary Search / Find Peak Element System design Space play · ←→ step · R restart

Problem

A peak is an item strictly greater than the items right next to it. Imagine the list is surrounded on both sides by minus infinity, so the first and last items only need to beat their one real neighbor.

Given nums, where neighbors are never equal, return the index of a peak. The examples below each have exactly one peak. Your solution must run in O(log n) time.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • nums[i] ≠ nums[i + 1] for every valid i

Examples: pick one to animate

Solutions

TimeO(log n) SpaceO(1)

Time: Each step discards half of the range, so about log2(n) steps.

Space: Only lo, hi and mid are stored.

Compare nums[mid] with nums[mid + 1]. If the path climbs, a peak is to the right (lo = mid + 1). If it falls, a peak is at mid or to its left (hi = mid). The edges at minus infinity guarantee one exists.