All problems
0536HardArrayStackMonotonic Stack

Sightlines Down the Mast Row

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1944Number of Visible People in a Queue

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A survey line carries radio masts, listed left to right in masts by height. No two masts are the same height.

An engineer standing on top of mast i faces the right-hand end of the line. For a mast j further along, that is with j > i, the engineer can see mast j when every mast standing between them is shorter than mast i and shorter than mast j. Nothing else blocks the view.

Return an array whose entry i is the number of masts to the right of mast i that the engineer on mast i can see.

Examples

Example 1

Input
masts = [7, 3, 5, 2, 4]
Output
[2, 1, 2, 1, 0]

From mast 0, of height 7, the masts of height 3 and 5 are visible, while the ones of height 2 and 4 are hidden behind the mast of height 5. From mast 2, of height 5, the masts of height 2 and 4 are both visible.

Example 2

Input
masts = [4, 3, 2, 1]
Output
[1, 1, 1, 0]

The heights fall away to the right, so from any mast every mast beyond it is visible: 3 from the first, then 2, then 1, then none.

Example 3

Input
masts = [1, 2, 3, 4]
Output
[1, 1, 1, 0]

From mast 0 the mast of height 2 is visible; the mast of height 3 is not, because the mast of height 2 between them is not shorter than mast 0. The same holds along the line.

Constraints

  • n == masts.length
  • 1 <= n <= 10^5
  • 1 <= masts[i] <= 10^5
  • The heights are all different.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def visible_masts(masts: list[int]) -> list[int]:
Java
public int[] visibleMasts(int[] masts)
September 7
Apply