Drill

ProblemsPython › patterns

Where the climb turns into a descent

mediumpatternsBinary searchArraysPython

A pressure trace rises to a single peak and then falls away. The analysis wants the position of the peak, and the traces are long.

peak_position(trace: list<int>) → int

Solve it in the editor →

Where you start

def peak_position(trace: list[int]) -> int:
    

Worked examples

CallResult
peak_position([1, 3, 5, 4, 2])2
peak_position([1, 2, 3])2
peak_position([9, 5, 1])0
peak_position([7])0

Hint

Compare a reading with the one after it. Still climbing means the peak is further right; already falling means it is here or to the left.

Reference solution in Python
def peak_position(trace: list[int]) -> int:
    if not trace:
        return -1
    lo, hi = 0, len(trace) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if trace[mid] < trace[mid + 1]:
            lo = mid + 1
        else:
            hi = mid
    return lo

The same problem in another language

More patterns problems in Python