The Runtime Theory
medium

Find Peak Element

Find any index that is a local peak (greater than both neighbors). Use binary search over indices for O(log n) time and O(1) space.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

The machine must find any index where nums[i] > nums[i-1] and nums[i] > nums[i+1] — a local peak. A linear scan is O(n), but the array's structure guarantees a peak exists, so binary search can halve the space: look at mid, compare it with mid+1. If nums[mid] < nums[mid+1], the array is ascending at mid, and a peak must exist somewhere to the right; otherwise one exists to the left (including at mid itself). No array-wide sort or comparison with both neighbors is needed.

python
def find_peak_element(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < nums[mid + 1]:
            lo = mid + 1
        else:
            hi = mid
    return lo

Steps: (1) binary search over indices, (2) compare mid with mid+1 to decide which half must contain a peak, (3) converge on a single index — the gradient guarantees termination.

Time is O(log n) with O(1) space — the greedy descent always finds a peak, not necessarily the highest one.

Trickiest edge cases: the implicit -∞ boundaries — nums[-1] = nums[n] = -∞, so the first or last element can be the peak (e.g. a strictly ascending array peaks at the last index); arrays of length 1 are already a peak; equal adjacent values make the comparison ambiguous, which is why the problem guarantees distinct neighbors.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.