HardArrayBinary Search

Find in Mountain Array

LeetCode
1 approach, code in all languages

A mountain array is an array that strictly increases up to a single highest element and then strictly decreases afterwards. You are given such an array wrapped behind an interface: you cannot read it directly, but you can call get(i) to fetch the value at position i and length() to learn the size. Calls to get are treated as expensive, so the number of them should be kept small.

Given a target value, return the smallest index whose value equals the target. If the target does not appear anywhere in the mountain array, return -1.

Example 1

Input: mountainArr = [1, 2, 3, 4, 5, 3, 1], target = 3

Output: 2

The value 3 appears at index 2 on the rising side and again at index 5 on the falling side. The smallest such index is 2.

Example 2

Input: mountainArr = [0, 1, 2, 4, 2, 1], target = 3

Output: -1

There is no element equal to 3 anywhere in the mountain, so the answer is -1.

Constraints

  • 3 <= mountainArr.length() <= 10^4
  • 0 <= target <= 10^9
  • 0 <= mountainArr.get(i) <= 10^9
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now