Number of Visible People in Queue — Monotonic Stack
Advertisement
Problem 279 · Number of Visible People in a Queue
Difficulty: Medium · Pattern: Monotonic Decreasing Stack
Person i can see person j (j > i) if all people between them are shorter than both.
Solutions
# Python
def canSeePersonsCount(heights):
n = len(heights); ans = [0]*n; stack = []
for i in range(n-1, -1, -1):
count = 0
while stack and stack[-1] < heights[i]:
stack.pop(); count += 1
if stack: count += 1 # see the blocking taller person
ans[i] = count
stack.append(heights[i])
return ans
// Java
public 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--) {
int count=0;
while (!stack.isEmpty() && stack.peek()<heights[i]) { stack.pop(); count++; }
if (!stack.isEmpty()) count++;
ans[i]=count; stack.push(heights[i]);
}
return ans;
}
Complexity
- Time: O(n)
- Space: O(n)
Advertisement