Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Find a value in a mountain array

Hard · Target 25 minutes · Binary search · Type asked atGoogle

A mountain array strictly increases to a single peak and then strictly decreases. Given a mountain array a and a target, return the smallest index i with a[i] = target, or −1 if there is none. Reading an element is expensive: use O(log n) reads.

Examples

InputOutputWhy
a = [1, 2, 3, 4, 5, 3, 1], target = 323 appears at indices 2 and 5; the smaller is 2.
a = [0, 1, 2, 4, 2, 1], target = 3-1
a = [1, 5, 2], target = 22

Constraints

  • 3 ≤ n ≤ 10⁴
  • 0 ≤ a[i], target ≤ 10⁹
  • a is a mountain array

Hints

Hint 1

A value can appear at most twice: once on the way up and once on the way down.

Hint 2

Find the peak first with the slope test from the previous problem.

Hint 3

Then run a normal lower-bound search on a[0..peak] (ascending). Only if that fails, search a[peak + 1..n − 1], which is descending, so the comparison flips.

Where people lose marks

  • Searching the falling side with the ascending comparison.
  • Searching the falling side first, which returns the larger of two indices.
  • Including the peak in both side searches, then reading past the end when p = n − 1 (impossible for a mountain, but cheap to guard).
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.