A peak element is one strictly greater than its neighbours (positions off the ends count as −∞). Given an array where no two adjacent values are equal, return the index of a peak in O(log n). For the test inputs here there is exactly one peak.
findPeak(nums)
Input format: space-separated integers (non-empty).
[1, 3, 2] // → 1
[1, 2, 3, 1] // → 2
[5, 4, 3, 2, 1] // → 0
A peak is a local maximum — bigger than both neighbors. There could be several scattered through the array, and you only need any one. The array isn't sorted, so binary search seems out of reach — but binary search only needs a way to look at a middle position and confidently discard one side as guaranteed not to contain the answer, while the other side is guaranteed to still have it.
Compare the middle to its right neighbor:
At every step, the current range [lo, hi] is guaranteed to contain at least one peak — that's what justifies discarding half each time.
Each comparison halves the range while preserving that guarantee, so it shrinks to a single index in time proportional to the array's logarithm. A linear scan checking every element's neighbors takes time proportional to the array's length; this needs only local slope information — a rise must eventually crest, a fall must have come from somewhere.
def find_peak(nums):
lo = 0
hi = len(nums) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.