KatInterview

Line of Sight Counts for Each Person in a Row

Stacks & QueuesModel answer
MediumModel answerStacks & Queuesmonotonic-stackarraysamortized-analysis

Last updated

For each person in a row, count how many people further right they can see when anyone standing between must be shorter than both of them. Needs an O(n) approach.

Line of sight in a queue

A row of n people faces forward. You are given an integer array heights, where heights[i] is the height of the person at position i (left to right).

Person i can see person j to their right (j > i) exactly when every person standing strictly between them is shorter than both of them:

heights[k] < min(heights[i], heights[j]) for all i < k < j.

Adjacent people (j = i + 1) always see each other, since nobody is between them.

For each position i, compute how many people to the right of i are visible to person i.

Input

  • heights: an array of n integers.

Output

  • An array ans of length n, where ans[i] is the number of people to the right of i that person i can see.

Example

heights = [10, 6, 8, 5, 11, 9]
ans     = [3, 1, 2, 1, 1, 0]

Person 0 (height 10) sees the 6, the 8 and the 11. The 5 is hidden behind the 8, and the 9 is hidden behind the 11.

Another case worth checking is [5, 5, 7], which gives [1, 1, 0]. The first person cannot see the 7, because the middle 5 is not strictly shorter than min(5, 7).

Constraints

  • 1 <= n <= 100000
  • 1 <= heights[i] <= 10^9
  • Heights may repeat.

What to provide

Describe your approach, explain why it is correct, give its time and space complexity, and write the code. A solution that checks every pair is too slow at this input size, so aim for something near linear.

Hints

Hint 1

Consider scanning from right to left. Which of the people you have already passed could still matter to someone further left?

Hint 2

Keep a stack of heights that is strictly decreasing from bottom to top. When a new person arrives, everyone on the stack who is shorter than them is visible to them, and also hidden from everyone further left.

Hint 3

After removing the shorter people, if the stack is not empty, the top is at least as tall as the current person and is visible. If it is exactly equal in height, it is also hidden from everyone further left and should be removed. Stop there, and do not count anything deeper.