AlgoMaster Logo

Number of Visible People in a Queue

heights=[10, 6, 8, 5, 11, 9]
1public int[] canSeePersonsCount(int[] heights) {
2    int n = heights.length;
3    int[] result = new int[n];
4    Stack<Integer> stack = new Stack<>();
5
6    for (int i = n - 1; i >= 0; i--) {
7        int visibleCount = 0;
8
9        while (!stack.isEmpty() && heights[i] > heights[stack.peek()]) {
10            stack.pop();
11            visibleCount++;
12        }
13
14        if (!stack.isEmpty()) {
15            visibleCount++;
16        }
17
18        result[i] = visibleCount;
19        stack.push(i);
20    }
21
22    return result;
23}
0 / 32
heights10061825311495000000resultstack