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

The top of a mountain array

Easy · Target 10 minutes · Binary search · Type asked atGoogleAmazonHudson River Trading

A mountain array strictly increases to a single highest element and then strictly decreases: there is an index p with 0 < p < n − 1 such that a[0] < … < a[p] > … > a[n − 1]. Given a mountain array, return p in O(log n) comparisons.

Examples

InputOutputWhy
a = [0, 1, 0]1
a = [0, 10, 5, 2]1
a = [1, 3, 5, 7, 9, 8]4

Constraints

  • 3 ≤ n ≤ 10⁵
  • 0 ≤ a[i] ≤ 10⁶
  • a is a mountain array

Hints

Hint 1

Compare a[mid] with a[mid + 1]. What does each outcome say about where the peak is?

Hint 2

If a[mid] < a[mid + 1], mid is on the way up and the peak is to its right. If a[mid] > a[mid + 1], mid is the peak or on the way down.

Hint 3

So "a[i] > a[i + 1]" is false then true along the array, and the peak is the first index where it is true.

Where people lose marks

  • Comparing a[mid] with a[mid − 1] and a[mid + 1] both, and then needing special cases at the ends.
  • Letting hi start at n, so that mid can be n − 1 and a[mid + 1] is read past the end.
  • Returning the peak value instead of its index.
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.