Problem Description
Given a mountain array (an array where values first strictly increase to a peak element then strictly decrease), find and return the index of the peak element. The solution must have O(log(n)) time complexity.
Key Insights
- The array is strictly increasing up to a peak and then strictly decreasing.
- A binary search technique is applicable because the array exhibits a single transition point (peak) between increasing and decreasing order.
- By comparing mid and mid+1, we can decide which half of the array to continue the search in.
Space and Time Complexity
Time Complexity: O(log(n)) - The binary search approach reduces the search interval by half at each step. Space Complexity: O(1) - Only constant extra space is used.
Solution
We use a binary search strategy:
- Initialize two pointers, left and right, at the beginning and end of the array.
- In each iteration, calculate mid. If arr[mid] is less than arr[mid + 1], then the peak is in the right half; otherwise, it is in the left half.
- When left equals right, we have found the peak index. This approach leverages the mountain array properties and ensures an O(log(n)) solution.