1496. Mountain Above the Line

Medium3.5 points estimatedBinary SearchInteractiveArray

Elevation readings along a hiking trail are hidden behind a MountainArray: they rise strictly to one peak and then fall strictly, with the peak neither first nor last. You cannot see the array directly; call mountain.length() for its size and mountain.get(i) for the reading at index i (0-based).

Given threshold, return how many indices hold a reading of at least threshold; return 0 when even the peak is lower. Find the peak with a binary search comparing get(mid) and get(mid + 1), then binary search each slope for the point where readings reach the threshold. You may call mountain.get at most 100 times. Target O(log n) time and O(1) extra space.

Example 1

Input:
mountain = [1,5,9,14,10,6,2], threshold = 6
Output:
4
Explanation:

The readings 9, 14, 10 and 6 are at least 6, giving a count of 4.

Example 2

Input:
mountain = [0,3,8,4,1], threshold = 9
Output:
0
Explanation:

The peak is 8, which is below the threshold of 9, so no reading qualifies.

Example 3

Input:
mountain = [2,4,6,8,7,5,3,1], threshold = 3
Output:
6
Explanation:

The readings 4, 6, 8, 7, 5 and 3 are at least 3; only 2 and 1 fall short, giving 6.

Constraints

3 ≤ length ≤ 104; 0 ≤ values ≤ 109; 0 ≤ threshold ≤ 109; at most 100 calls to get

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Calls
You may call MountainArray.get(index), MountainArray.length() at most 100 times per case. It is provided; you do not write it.

Expected complexity

Time
O(log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…