1712. Mutual Line of Sight

Hard7.5 points estimatedMonotonic StackStackArray

Fans stand in a single row at an outdoor concert, and heights[i] is the height of the fan at position i. Two fans at positions i < j can see each other when nobody standing strictly between them is taller than the shorter of the two, so people of equal height do not block each other. Return the number of pairs (i, j) with i < j that can see each other, as a 64-bit integer. The row holds 1 to 200000 fans with heights between 1 and 10^9. Aim for O(n) time and O(n) space by keeping a non-increasing stack of height groups: a newcomer sees every shorter fan it pops, the whole group of equal-height fans, and one taller fan left below that group.

Example 1

Input:
heights = [4,2,3,1,5]
Output:
7
Explanation:

Four neighbouring pairs see each other, plus (0,2), (2,4) and (0,4), giving 7.

Example 2

Input:
heights = [5]
Output:
0
Explanation:

A single fan has nobody to pair with.

Example 3

Input:
heights = [2,2,2]
Output:
3
Explanation:

All three pairs see each other because equal heights never block.

Constraints

1 ≤ n ≤ 2 * 105

1 ≤ heights[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…