FastPrepFind in Mountain Array

Find in Mountain Array

Bloomberg LP logoBloomberg LP● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

A mountain array strictly increases to one peak and then strictly decreases.

Given a mountain array mountain and an integer target, return the smallest index whose value equals target. Return -1 when the target is absent.

Your algorithm must use logarithmic-time binary searches rather than scanning the array.

Function

findInMountainArray(mountain: int[], target: int) → int

Examples

Example 1

mountain = [1,2,3,4,5,3,1]target = 3return = 2

Value 3 appears on both slopes; return its smaller index 2.

Example 2

mountain = [0,1,2,4,2,1]target = 3return = -1

The target is absent.

Example 3

mountain = [1,5,2]target = 5return = 1

The target is the peak.

Constraints

  • 3 <= mountain.length <= 100000.
  • -10^9 <= mountain[i], target <= 10^9.
  • There is exactly one peak, with at least one value on each side.
  • The left slope is strictly increasing and the right slope is strictly decreasing.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int findInMountainArray(int[] mountain, int target) {
    // Write your code here.
}
mountain[1,2,3,4,5,3,1]
target3
expected2
Checking account…