1689. Bookend Peaks

Medium3.5 points estimatedMonotonic StackStackArrayCounting

A hiker records the altitude of every checkpoint along a ridge in nums. A stretch of consecutive checkpoints is called a bookend peak when its first and its last altitude are both equal to the highest altitude inside that stretch. A stretch made of a single checkpoint always counts.

Return the number of bookend peaks among all contiguous stretches, as a long (the count can exceed the 32-bit range). Keep a stack of groups (value, count) whose values never increase from bottom to top: a new altitude pops smaller groups, and if the group below has the same value it pairs with every earlier copy there. This gives O(n) time and O(n) space; checking all O(n^2) stretches is too slow for the largest inputs.

Example 1

Input:
nums = [3,1,3]
Output:
4
Explanation:

The three single elements count, and so does [3, 1, 3] whose ends equal its maximum 3; the other subarrays do not qualify, giving 4.

Example 2

Input:
nums = [5,5,5]
Output:
6
Explanation:

Every one of the 6 subarrays has equal ends that are also its maximum.

Example 3

Input:
nums = [1,2,3]
Output:
3
Explanation:

Only the three single-element subarrays qualify.

Constraints

1 ≤ n ≤ 105; 1 ≤ nums[i] ≤ 109

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

Expected complexity

Time
O(n)
Space
O(n)

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…