Menu
CoddyTech

Find Peak Element

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

The array nums climbs and then falls: each value is larger than the one before it up to some index, and each value after that index is smaller than the one before it. Either part may be empty, so the array may only climb or only fall. The value at the turning index is the peak, the only value larger than every neighbour it has.

Return the index of the peak, in O(log n) time.

Function

findPeakElement(nums: integer-array) → integer
numsinteger-array
the values, rising to one peak and then falling
Returnsinteger
the index of the peak

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -106 ≤ nums[i] ≤ 106
  • nums[i] != nums[i+1] for every valid i.
  • nums strictly increases up to one index and strictly decreases after it, so there is exactly one peak.

Examples

Input
nums = [2, 5, 9, 4, 1]
Output
2
Explanation
The values rise through 2, 5 and 9, then fall through 4 and 1. The turn is at 9, index 2.
challenge icon

Follow-up

In a grid where no two neighbouring cells are equal, a peak is a cell larger than its up to four neighbours. Can you find one without reading every cell?

Reset code
def findPeakElement(nums):
    # Write code here

Test #1

Test #2

Test #3

Argument

nums = [2, 5, 9, 4, 1]

Expected Output

2