AlgoMaster Logo

Number of Visible People in a Queue

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest way to solve this problem is to use a double loop. For each person in the queue, we can look at each subsequent person and determine if they're visible. A person is visible if all the people between them and the current person in the focus are shorter. Once we find a taller person, all subsequent people are not visible.

Algorithm:

  1. Initialize an array result to store the number of visible people for each person in the queue.
  2. For each person in the queue located at index i, look at each subsequent person j (where j > i).
  3. If the person at j is taller than the person at i, they are visible, and we can break out of the loop since no one beyond them can be visible to person i.
  4. Continue counting visible people for person i until a taller person is encountered.
  5. Repeat for all people in the queue.

Code:

2. Monotonic Stack

Intuition:

To reduce the time complexity, we can use a stack to maintain a list of indices. This stack helps us efficiently track the tallest visible people as we traverse the queue from right to left. By using a stack, we can keep removing shorter people who are no longer visible whenever we encounter a taller person farther in the queue.

Algorithm:

  1. Initialize a stack to keep indices and an array result to store answer.
  2. Traverse the queue from right to left.
  3. For each person encountered:
    • Pop persons from the stack while the current person is taller, since they won't be visible anymore.
    • Count the popped persons as visible.
    • If the stack isn't empty, it means there's a person who is taller than the current one, making them visible as well.
    • Push the current person's index onto the stack.
  4. Repeat until the whole queue is processed.

Code: