oneby7

Binary Search Lower and upper bounds

232. Peak Index in a Mountain Array

Medium

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]

Output: 4

Explanation: 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]

Output: 3

Explanation: 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]

Output: 1

Explanation: 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.

nums = [1, 3, 8, 12, 4]

Constraints

  • 3 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • There is an index p with 0 < p < nums.length − 1 such that nums[0] < nums[1] < … < nums[p] and nums[p] > nums[p + 1] > … > nums[nums.length − 1]

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.