AceYourInterviews
Checking sign-in…

64. Find a Peak Element

CoreSlope-guided search retaining some strict peak

Find a position whose value is greater than each immediate neighbor that exists. At the ends, only the one real neighbor needs to be considered.

A peak need not be the global maximum, and multiple answers may be valid. The conceptual values outside the array are lower than every allowed input value.

Example 1

Input

[1,2,1,3,5,6,4]

Output

Any of 1 or 5; optimized returns 5

Explanation: The slope at mid=3 is rising, so a peak exists to the right even though another peak lies to the left.

Example 2

Input

[3,2,1]

Output

0

Explanation: The left endpoint is a peak relative to conceptual −infinity on its outside.

Example 3

Input

[MIN]

Output

0

Explanation: No representable int sentinel is needed; endpoint existence is defined through missing neighbors.

Constraints

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • Adjacent values are unequal. Return any strict peak index.
Hints
Hint 1

A rising edge guarantees some peak in the uphill direction before the array ends.

Hint 2

The active interval’s outside edges should face downward away from it.

Hint 3

Compare mid with mid+1, keep the uphill side, and stop when one index remains.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Multiple peaks: retain one uphill region

[1,2,1,3,5,6,4]
5