FastPrepPeak of an Increasing-Then-Decreasing Array

Peak of an Increasing-Then-Decreasing Array

Snap Inc. logoSnap Inc.● MediumFULLTIMEONSITE INTERVIEW

Problem statement

You are given an array nums. The numbers strictly increase up to one position, called the peak, and then strictly decrease until the end of the array.

Return the index of the peak. The interview asked for a binary search, so try to solve this in O(log n) time.

Follow-up to think about (not judged): suppose neighbors can be equal, so the numbers never go down before the peak and never go up after it. Can you still use binary search?

Function

findPeak(nums: int[]) → int

Examples

Example 1

nums = [1,3,5,4,2]return = 2

The numbers go up through 1, 3, 5 and then down through 4, 2. The largest number 5 is at index 2.

Example 2

nums = [0,10,5,2]return = 1

There is one step up, from 0 to 10, and then the numbers go down. The peak is at index 1.

Example 3

nums = [-5,-2,-9]return = 1

All the numbers can be negative. -2 is larger than both neighbors, so the peak is at index 1.

Constraints

  • 3 <= nums.length <= 5000
  • -10^9 <= nums[i] <= 10^9
  • 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].

More Snap Inc. problems

See Snap Inc. hiring insights
Saved
public int findPeak(int[] nums) {
    // Write your code here.
}
Checking account…