Number of Visible People in a Queue

hard monotonic stack

Problem

There are n people in a queue, all with distinct heights, listed left to right in heights. Person i can see person j to their right when everyone standing between them is shorter than both of them (formally, min(heights[i], heights[j]) > max of the heights in between).

Return an array answer where answer[i] is the number of people the i-th person can see looking to their right.

Inputheights = [10, 6, 8, 5, 11, 9]
Output[3, 1, 2, 1, 1, 0]
Person 0 (height 10) sees 6, 8 and 11: the 5 hides behind 8, and 11 blocks everyone past it.

def can_see_persons_count(heights):
    n = len(heights)
    ans = [0] * n
    stack = []
    for i in range(n - 1, -1, -1):
        while stack and stack[-1] < heights[i]:
            stack.pop()
            ans[i] += 1
        if stack:
            ans[i] += 1
        stack.append(heights[i])
    return ans
function canSeePersonsCount(heights) {
  const n = heights.length;
  const ans = new Array(n).fill(0);
  const stack = [];
  for (let i = n - 1; i >= 0; i--) {
    while (stack.length && stack[stack.length - 1] < heights[i]) {
      stack.pop();
      ans[i]++;
    }
    if (stack.length) ans[i]++;
    stack.push(heights[i]);
  }
  return ans;
}
int[] canSeePersonsCount(int[] heights) {
    int n = heights.length;
    int[] ans = new int[n];
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = n - 1; i >= 0; i--) {
        while (!stack.isEmpty() && stack.peek() < heights[i]) {
            stack.pop();
            ans[i]++;
        }
        if (!stack.isEmpty()) ans[i]++;
        stack.push(heights[i]);
    }
    return ans;
}
vector<int> canSeePersonsCount(vector<int>& heights) {
    int n = heights.size();
    vector<int> ans(n, 0);
    vector<int> stack;
    for (int i = n - 1; i >= 0; i--) {
        while (!stack.empty() && stack.back() < heights[i]) {
            stack.pop_back();
            ans[i]++;
        }
        if (!stack.empty()) ans[i]++;
        stack.push_back(heights[i]);
    }
    return ans;
}
Time: O(n) Space: O(n)