Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1944: Number of Visible People in a Queue

In this guide, we solve Leetcode #1944 Number of Visible People in a Queue in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Stack, Array, Monotonic Stack

Intuition

We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.

Each element is pushed and popped at most once, yielding a linear-time scan.

Approach

Maintain a stack that is either increasing or decreasing, depending on the query.

When the invariant is broken, pop and resolve answers for those indices.

Steps:

  • Scan elements once.
  • Pop while the monotonic condition is violated.
  • Use stack indices to update answers.

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. Person 1 can see person 2. Person 2 can see person 3 and 4. Person 3 can see person 4. Person 4 can see person 5. Person 5 can see no one since nobody is to the right of them.

Python Solution

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

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy