Problem Description
Given an array of integers, a peak element is defined as an element that is strictly greater than its neighbors. Given that nums[-1] and nums[n] are considered -∞, find any index of a peak element using an algorithm that runs in O(log n) time.
Key Insights
- Use a binary search strategy to achieve the required O(log n) time complexity.
- At each step, compare the middle element with its right neighbor to decide which half to search.
- Due to the -∞ boundaries, there is always at least one peak in the array.
Space and Time Complexity
Time Complexity: O(log n) Space Complexity: O(1)
Solution
We use a binary search approach by maintaining two pointers: low and high. We calculate a mid index and check if it is a peak by comparing it with its neighbors. If the element to the right of mid is greater, then a peak must exist in the right half of the array; otherwise, it will be in the left half. This greedy move is valid due to the boundary conditions where the ends are effectively -∞. By continually narrowing the search space, we can efficiently find a peak element.