mediumArraysPattern: Modified binary search
Peak Element Index Solution
Problem Statement
Given a sorted array of integers where the elements are either monotonically increasing and then decreasing, or vice versa, around a single peak element, find the index of the peak element.
Examples
Example 1:
Input:[1,2,3,1]
Output:2
Example 2:
Input:[1,3,20,4,1,0]
Output:2
Constraints
- 1 <= temperatures.length <= 1000
- -2^31 <= temperatures[i] <= 2^31 - 1
Time: O(log n) Space: O(1)
The optimal approach is to use a modified binary search algorithm, which can find the peak element in O(log n) time complexity by repeatedly dividing the search space in half.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
