Binary Search Lower and upper bounds
232. Peak Index in a Mountain Array
You are given an array of integers nums that is a mountain. Return the index of its peak.
An array is a mountain when its values rise strictly up to one element, the peak, and then fall strictly
until the end. The peak is never the first or the last element, so the array rises at least once and falls at
least once. In [1, 6, 4], the peak is 6 at index 1.
Indexes start at 0. Aim for O(log n) time.
Example 1
Input: nums = [2, 5, 11, 17, 23, 20, 8, 1]
4Explanation: The values rise from 2 to 23 and then fall to 1. The peak is 23, at index 4.
Example 2
Input: nums = [-40, -31, -18, -7, -12]
3Explanation: Every value is negative. The array rises to −7 at index 3 and falls once after it, to −12.
Example 3
Input: nums = [-1000000000, 1000000000, 999999999]
1Explanation: The shortest mountain has three elements, and its peak is always the middle one.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
3 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109- There is an index
pwith0 < p < nums.length − 1such thatnums[0] < nums[1] < … < nums[p]andnums[p] > nums[p + 1] > … > nums[nums.length − 1]
Clarifying questions
What you would ask an interviewer before writing any code.