InferenceAI

Enter at least two characters to search.

Start free

Find a Peak

mediumBinary Search25 min25 XP

An element is a peak if it is strictly greater than its neighbours (positions outside the list count as −∞-\infty). Adjacent values are never equal.

Return the index of the leftmost peak, so the answer is unique.

Requirements

  • A linear scan is accepted, but try the O(log⁡n)O(\log n) idea too: always move towards the larger neighbour.

Constraints

  • 1≤n≤10001 \le n \le 1000

Examples

EXAMPLE WALKTHROUGHsingle peak

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3,1]]
TASKfind_a_peak()
EXPECTED OUTPUT2

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [1,2,3,1]

Output: 2

Explanation: single peak

Input: nums = [1,2,1,3,5,6,4]

Output: 1

Explanation: two peaks

Input: nums = [5]

Output: 0

Explanation: single element

Hint 1

Compare each element with its neighbours.

Hint 2

For the logarithmic version: if nums[mid] < nums[mid + 1], a peak exists to the right.

Topics

DSABinary SearchPython