Skip to content

1944. Number of Visible People in a Queue 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> canSeePersonsCount(vector<int>& heights) {
    const int n = heights.size();
    vector<int> ans(n);
    stack<int> stack;

    for (int i = 0; i < n; ++i) {
      while (!stack.empty() && heights[stack.top()] <= heights[i])
        ++ans[stack.top()], stack.pop();
      if (!stack.empty())
        ++ans[stack.top()];
      stack.push(i);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int[] canSeePersonsCount(int[] heights) {
    final int n = heights.length;
    int[] ans = new int[n];
    Deque<Integer> stack = new ArrayDeque<>();

    for (int i = 0; i < n; ++i) {
      while (!stack.isEmpty() && heights[stack.peek()] <= heights[i])
        ++ans[stack.pop()];
      if (!stack.isEmpty())
        ++ans[stack.peek()];
      stack.push(i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def canSeePersonsCount(self, heights: List[int]) -> List[int]:
    ans = [0] * len(heights)
    stack = []

    for i, height in enumerate(heights):
      while stack and heights[stack[-1]] <= height:
        ans[stack.pop()] += 1
      if stack:
        ans[stack[-1]] += 1
      stack.append(i)

    return ans
Back to top