HardNo. 1944

Number of Visible People in a Queue — LeetCode 1944 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic Stack
Reading time
3 min

The problem

There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.

Example

Input
heights = [10,6,8,5,11,9]
Output
[3,1,2,1,1,0]
Explanation
Person 0 can see person 1, 2, and 4.

Python solution

PythonSolution
class Solution:
    def canSeePersonsCount(self, heights: List[int]) -> List[int]:
        n = len(heights)
        ans = [0] * n
        stk = []
        for i in range(n - 1, -1, -1):
            while stk and stk[-1] < heights[i]:
                ans[i] += 1
                stk.pop()
            if stk:
                ans[i] += 1
            stk.append(heights[i])
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1944. Number of Visible People in a Queue is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium
0853Car FleetMedium

Frequently asked questions

How hard is LeetCode 1944. Number of Visible People in a Queue?

LeetCode 1944. Number of Visible People in a Queue is rated Hard on LeetCode.

What is the time complexity of LeetCode 1944. Number of Visible People in a Queue?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1944. Number of Visible People in a Queue?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1944. Number of Visible People in a Queue cover?

LeetCode 1944. Number of Visible People in a Queue is tagged Stack, Array and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.