2dbi

Find peak element

viaLeetCode

Problem Find any peak element — strictly greater than its neighbors — and return its index (nums[-1] and nums[n] are conceptually −∞). Multiple peaks: return any.

Input / Output

  • Input: int array nums (adjacent elements distinct). Output: a peak index.

Constraints

  • n up to 10^5; O(log n) required — the linear scan is the baseline being beaten.

Example

  • [1,2,3,1] → 2; [1,2,1,3,5,6,4] → 1 or 5.

Expected approach

  • Binary search on slope: compare nums[mid] with nums[mid+1]; rising (nums[mid] < nums[mid+1]) → a peak exists to the right (lo = mid+1); falling → peak at mid or left (hi = mid). The −∞ boundaries guarantee a peak in the retained half — that invariant argument is the interview substance. Terminates at lo == hi. O(log n)/O(1). 2D peak (column-max + slope) is the classic escalation.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account