Taro Logo

Number of Visible People in a Queue

#2 Most AskedHard
1 view
Topics:
ArraysStacks

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.

A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).

Return an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.

Example 1:

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.

Example 2:

Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]

Constraints:

  • n == heights.length
  • 1 <= n <= 105
  • 1 <= heights[i] <= 105
  • All the values of heights are unique.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected range of the height values in the input array, and can we have duplicate heights?
  2. What should we return if the input array is empty or contains only a single person?
  3. Does a person's line of sight get completely blocked by someone of equal height, or can they still see past them?
  4. What is the exact return type and format expected? Should it be a new array of integers of the same length?
  5. Can the heights include negative numbers or zeros, or are they guaranteed to be positive integers?

Brute Force Solution

Approach

To find out how many people each person in a line can see to their right, the brute force approach simply has every single person look straight ahead and count every person standing in front of them until they hit someone taller who blocks their view.

Here's how the algorithm would work step-by-step:

  1. Stand at the very first person at the front of the line.
  2. Have this person look to their right at the next person standing immediately beside them and count that person as visible.
  3. Continue looking further down the line one person at a time, counting each person seen.
  4. Stop counting to the right the exact moment someone taller blocks the view, because nobody beyond that taller person can be seen.
  5. Record the total count of people seen by this starting person.
  6. Walk over to the next person in line and repeat the exact same process of looking to the right and counting until blocked.
  7. Continue this process for every single person in the line until everyone has finished looking and counting.

Code Implementation

def can_see_persons_count(heights):    result_counts = [0] * len(heights)    # Iterate through every person in the queue to calculate their individual view count    for current_index in range(len(heights)):        visible_count = 0        max_seen_height = 0        for scan_index in range(current_index + 1, len(heights)):            # Always count the person immediately next in line since no one blocks them yet            if scan_index == current_index + 1:                visible_count += 1                max_seen_height = heights[scan_index]            elif heights[scan_index] > max_seen_height:                # Count taller people who manage to peek over previous obstacles in the line                visible_count += 1                max_seen_height = heights[scan_index]            # Stop scanning rightward the exact moment someone blocks the view entirely            if heights[scan_index] >= heights[current_index]:                break        result_counts[current_index] = visible_count    return result_counts

Big(O) Analysis

Time Complexity
O(n²) – For each of the n people in the queue, we iterate to their right to count everyone visible until a taller person blocks the view. The first person might scan up to n minus 1 people, the second person scans up to n minus 2 people, and this pattern continues down the line. Adding up these checks for all n individuals results in approximately n times n over 2 operations, which simplifies to O(n²).
Space Complexity
O(N) – To solve this problem efficiently using a monotonic stack, we maintain a stack of elements to keep track of people who are still visible to the right. In the worst-case scenario, such as when the line of people is strictly decreasing in height, every single person will be pushed onto this stack. Since there are N people in total, the stack will grow to store up to N integers simultaneously. Therefore, the auxiliary space complexity is strictly proportional to the input size N, resulting in O(N) extra memory usage.

Optimal Solution

Approach

Instead of checking every person one by one from the front, the optimal approach works backwards from the end of the line while keeping track of who is currently visible. This clever shortcut avoids repeatedly looking at the same people and lets us figure out how many people each person can see in a single pass.

Here's how the algorithm would work step-by-step:

  1. Imagine walking down the line starting from the very last person and moving toward the front.
  2. Keep a running list of people you can see as you move backwards, ensuring that anyone shorter who is blocked by a taller person is hidden from view.
  3. Whenever you encounter a new person, count how many people they are taller than in your current list by removing the shorter ones who would be blocked.
  4. Add one more to that count if there is still someone taller at the end who blocks the view further down the line.
  5. Record this total count for the person you are currently looking at.
  6. Finally, add this new person to the front of your running list of visible people so the next person in line can see who is ahead of them.
  7. Repeat this process until you reach the very first person in line.

Code Implementation

def can_see_persons_count(heights_of_people):
    total_people_count = len(heights_of_people)
    visible_count_array = [0] * total_people_count
    monotonic_stack = []

    # Traverse backwards to maintain a decreasing stack of visible people ahead.
    for person_index in range(total_people_count - 1, -1, -1):
        people_seen_count = 0
        
        # Remove shorter people who are blocked by the current taller person.
        while monotonic_stack and heights_of_people[person_index] > monotonic_stack[-1]:
            monotonic_stack.pop()
            people_seen_count += 1

        # Add one more if a taller person remains to block the further view.
        if monotonic_stack:
            people_seen_count += 1

        visible_count_array[person_index] = people_seen_count
        monotonic_stack.append(heights_of_people[person_index])

    return visible_count_array

Big(O) Analysis

Time Complexity
O(n) – As we iterate backwards from the last person to the first person in the array of size n, each element is pushed onto our tracking stack at most once and popped at most once. While there is an inner loop to pop shorter people who are blocked from view, this inner loop only processes elements that are permanently removed from the stack. Consequently, the total number of push and pop operations across the entire backward traversal is bounded by 2n. Therefore, the operations scale linearly with the input size, simplifying to a time complexity of O(n).
Space Complexity
O(N) – The auxiliary space is driven by a monotonic stack used as a running list to keep track of visible people as we iterate backwards through the queue. In the worst-case scenario, such as a strictly decreasing queue where every person can see everyone to their right, the stack will store all N elements. Therefore, the extra memory required scales linearly with the input size N.

Edge Cases

Empty or single-element array
How to Handle:
Return the array as is or with a single zero since no one is standing to the right.
Array with all elements in strictly decreasing order
How to Handle:
The monotonic stack will be empty for each person after checking, resulting in an answer of one for each person except the last.
Array with all elements in strictly increasing order
How to Handle:
Each person will see everyone to their right until the tallest person, resulting in a count of one for all except the last person who sees zero.
Array containing identical duplicate heights
How to Handle:
The monotonic stack logic handles duplicates by allowing visibility up to and including the first person who is equal or taller.
Extremely large array with maximum constraints
How to Handle:
The monotonic stack solution processes each element at most twice, ensuring optimal linear time complexity to prevent timeouts.
Heights containing negative numbers or zeros
How to Handle:
The relational comparison logic works identically regardless of sign since relative height differences dictate visibility.
0/8 completed