Find in Mountain Array
1 approach, code in every language
Problem description
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^40 <= target <= 10^90 <= mountainArr.get(i) <= 10^9
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free