I knew binary search was the answer pretty fast but explaining WHY it works took me longer than I'd like to admit.
Use binary search to find a peak by comparing the middle element with its neighbors. If the middle is greater than both neighbors, return it; otherwise, move towards the side with the larger neighbor. This works because the array has no equal adjacent elements, guaranteeing a peak exists in the direction of ascent.
Pro tip: Clarify edge cases upfront: arrays of length 1 or 2, and how boundaries are treated as negative infinity. This shows attention to detail and avoids off-by-one errors.
Restate the problem: find any peak in O(log n) time. Note that adjacent elements are never equal, and boundaries are negative infinity, so the ends can be peaks if they are greater than their single neighbor.
Explain that binary search is suitable because the peak condition allows us to discard half the array based on local comparisons, achieving logarithmic time.
While left <= right, compute mid. If mid is a peak (greater than both neighbors, considering boundaries), return mid. Otherwise, if the left neighbor is greater, search left; else search right.
Check for arrays of length 1 (return 0) and length 2 (return index of larger element). Also ensure boundary checks when mid is at the start or end.
State that time complexity is O(log n) and space is O(1). Walk through a small example to verify correctness.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.