Find in Mountain Array

Find in Mountain Array is a Hard Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Binary Search Patterns pattern, in the Find Min/Max in Rotated Sorted Array subpattern.

Problem statement

(This problem is an interactive problem.)

You may recall that an array arr is a mountain array if and only if:

- arr.length >= 3

- There exists some i with 0 < i < arr.length - 1 such that:

- arr[0] < arr[1] < ... < arr[i - 1] < arr[i]

- arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.

You cannot access the mountain array directly. You may only access the array using a MountainArray interface:

- MountainArray.get(k) returns the element of the array at index k (0-indexed).

- MountainArray.length() returns the length of the array.

Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

Example 1:

Input: mountainArr = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.

Example 2:

Input: mountainArr = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1.

Constraints:

- 3 <= mountainArr.length() <= 104

- 0 <= target <= 109

- 0 <= mountainArr.get(index) <= 109

Topics and companies

Topics: Array, Binary Search, Interactive.

Reported in interviews at Apple, Bloomberg, Quora.

How to practise Find in Mountain Array on Thita.ai

Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(log n), where n is the length of the array. Finding the peak takes O(log n), and each binary search (on the increasing and decreasing sides) also takes O(log n). time and O(1), as only a constant amount of extra space is used (no recursion or auxiliary data structures). space.

Open Find in Mountain Array in the code editor, or read the Find in Mountain Array editorial for a worked solution with its approach and complexity analysis.

Where Find in Mountain Array sits in the DSA pattern sheet

Problems related to Find in Mountain Array

Other problems that use the same Find Min/Max in Rotated Sorted Array and Binary Search Patterns techniques:

Preparing this workspace.