Rightward Visibility Counts in a Queue

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given an integer list heights containing n positive values ordered from index 0 (leftmost) to index n - 1 (rightmost), determine how many rightward positions each entry can observe.

From index i, a rightward index j (j > i) has a clear line of sight if and only if every intermediate index k (i < k < j) is strictly shorter than both endpoints:

heights[k] < min(heights[i], heights[j])   for all k with i < k < j

Put another way, scanning rightward from index i, you can observe a strictly rising chain of elements shorter than heights[i], plus the very first element whose value is at least heights[i] (which blocks everything beyond it). Adjacent indices (j = i + 1) have no intermediate indices between them, so index i always observes i + 1 whenever i + 1 < n.

Implement count_visible_right(heights) and return an integer list of length n whose i-th entry is the count of rightward indices observable from index i.

Examples

Example 1

  • Input: heights = [12, 5, 7, 9, 4, 15, 8]
  • Output: [4, 1, 1, 2, 1, 1, 0]
  • Explanation:
    • Index 0 (12) observes 5, 7, 9, and 15 (4 items): 4 at index 4 sits in a valley behind 9, and 8 at index 6 sits behind 15.
    • Index 1 (5) observes 7, which immediately blocks everything further right.
    • Index 2 (7) observes 9, which blocks everything further right.
    • Index 3 (9) observes 4 and 15 (2 items), while 15 blocks 8.
    • Index 4 (4) observes 15, index 5 (15) observes 8, and index 6 (8) has nothing to its right (0).

Example 2

  • Input: heights = [8, 3, 3, 8, 10]
  • Output: [2, 1, 1, 1, 0]
  • Explanation:
    • Because intermediate elements must be strictly shorter (<), ties block the view: index 0 (8) observes index 1 (3) and index 3 (8), while index 1 hides index 2 (3) and index 3 hides index 4 (10).
    • Each of indices 1, 2, and 3 observes only its immediate right neighbor, and index 4 observes 0.

Example 3

  • Input: heights = [6, 4, 2]
  • Output: [1, 1, 0]
  • Explanation: In a strictly descending sequence, each element observes its immediate right neighbor (6 sees 4; 4 sees 2), which hides every smaller value behind it.

Constraints

  • 1 <= len(heights) <= 100,000
  • 1 <= heights[i] <= 10^9

Step-by-step walkthrough

  1. Understand the visibility rule visually

    We are given a list heights of n entries arranged from left (0) to right (n - 1). For each index i, we want to count how many indices j to its right (j > i) have an unobstructed line of sight from i.

    Index i can observe index j when every intermediate index k (i < k < j) is strictly shorter than both heights[i] and heights[j]:

    heights[k] < min(heights[i], heights[j])   for every k with i < k < j
    

    Picture Example 1, heights = [12, 5, 7, 9, 4, 15, 8], as vertical bars while looking rightward from index 0 (height = 12):

    Height
      15 |                     #
      12 | # ----------------> # (12 sees 5, 7, 9, and 15; 15 blocks 8)
       9 | #           #       #
       8 | #           #       #   #
       7 | #       #   #       #   #
       5 | #   #   #   #       #   #
       4 | #   #   #   #   #   #   #
         +---------------------------
       i:  0   1   2   3   4   5   6
       h: 12   5   7   9   4  15   8
                           ^       ^-- hidden behind 15
                           +-- hidden in the valley behind 9
    

    Notice two direct consequences of this rule:

    1. Immediate neighbors always see each other (when j = i + 1, no index k lies strictly between them, so nothing can obstruct the view).
    2. Ties block the view, because the inequality heights[k] < min(...) is strict (<, not <=). In [8, 3, 3, 8, 10], the first 3 blocks index 0 (8) from seeing the second 3, and the second 8 blocks index 0 from seeing 10.
  2. Start with the brute-force scan and see why it times out

    The most direct way to compute visible_counts[i] is to stand at index i and scan rightward (j = i + 1, i + 2, ...), tracking tallest_between — the tallest value encountered so far strictly between i and j:

    • Whenever tallest_between < min(heights[i], heights[j]), index i sees index j.
    • As soon as heights[j] >= heights[i], stop scanning — index j is at least as tall as i and blocks everything further right.
    def count_visible_brute(heights):
        n = len(heights)
        visible_counts = [0] * n
        for i in range(n):
            visible = 0
            tallest_between = 0  # heights[k] >= 1, so 0 means nobody in between yet
            for j in range(i + 1, n):
                if tallest_between < min(heights[i], heights[j]):
                    visible += 1
                tallest_between = max(tallest_between, heights[j])
                if heights[j] >= heights[i]:
                    break
            visible_counts[i] = visible
        return visible_counts
    

    Why is this too slow when n = 100,000? Consider a strictly decreasing input like [100000, 99999, 99998, ..., 1]. No element to the right is ever >= heights[i], so the early break never triggers! Every index i scans all the way to n - 1, doing n * (n - 1) / 2 ≈ 5 * 10^9 loop iterations. We need an O(n) approach that avoids re-scanning the same suffix repeatedly.

  3. Key insight: visible elements form a strictly rising staircase

    Look rightward from index i (with height current_height = heights[i]). Every candidate j > i falls into one of two cases:

    • Case 1: heights[j] is shorter than current_height. Here min(current_height, heights[j]) = heights[j]. Thus i sees j if and only if heights[j] is strictly taller than everything between i and j. Walking right from i + 1, each visible shorter entry must set a new strict height record — forming an upward staircase (5 -> 7 -> 9 in [12, 5, 7, 9, 4, 15, 8], skipping 4 because 9 already shadowed it).
    • Case 2: heights[j] is at least as tall as current_height. Here min(current_height, heights[j]) = current_height. Index i sees only the very first position with heights[j] >= current_height (15 in Example 1), and its view stops right there.

    Notice what happened to 4 (heights[4] = 4) in [12, 5, 7, 9, 4, 15, 8]: once 9 (heights[3] = 9) sits to the left of 4, no index further left (i = 2, 1, 0) can ever see 4! Anyone left of 9 has 9 standing in between, and 9 > 4 violates heights[k] < min(heights[i], 4). Once 4 is shadowed by 9, we can discard 4 permanently.

  4. Maintain the staircase from right to left with a monotonic stack

    Because elements shadowed by a taller neighbor in front of them never become visible again to anyone further left, we can sweep from right to left (i = n - 1 down to 0) using a monotonic stack — an ordinary list used as a stack where heights stay strictly decreasing from bottom (stack[0], tallest and farthest right) to top (stack[-1], shortest and nearest right).

    Suppose we reach index i = 0 (current_height = 12) in [12, 5, 7, 9, 4, 15, 8], and stack currently holds the rising staircase to its right: [15, 9, 7, 5] (stack[-1] = 5 is closest to 12):

    Before i = 0 (current_height = 12):
      stack (bottom -> top): [15, 9, 7, 5]   <-- nearest on top (5, then 7, 9, 15)
    
    Phase 1 (pop strictly shorter):
      5 < 12 -> pop 5, visible = 1           (12 hides 5 from anyone further left)
      7 < 12 -> pop 7, visible = 2           (12 hides 7 from anyone further left)
      9 < 12 -> pop 9, visible = 3           (12 hides 9 from anyone further left)
      15 < 12 is False -> stop popping!
    
    Phase 2 (check first blocker >= 12):
      stack is [15] (non-empty!), so 12 also sees 15 -> visible = 4.
      15 stays on the stack because someone > 12 further left could still see 15 over 12!
    
    Phase 3 (push 12):
      stack becomes [15, 12]                 <-- still strictly decreasing bottom-to-top!
    
  5. Handle duplicate heights without off-by-one bugs

    Equal heights are the trickiest corner of this problem. Verify the == case on Example 2 (heights = [8, 3, 3, 8, 10]):

    1. Duplicate shorter values ([8, 3, 3, ...]): From the first 8 (i = 0), index 1 (3) is visible, whereas index 2 (3) is hidden because index 1 in between is not < 3.

      • At i = 1 (current_height = 3), when stack is [10, 8, 3], stack[-1] is 3 (not < 3), so Phase 1 pops 0 items.
      • Phase 2 sees stack is non-empty (stack[-1] == 3 >= 3), so visible += 1 (the first 3 sees the adjacent 3).
      • Critical rule: because stack[-1] == current_height, we must pop that duplicate 3 before pushing the new 3! Otherwise stack would become [10, 8, 3, 3], and index 0 (8) would pop both 3s and overcount.
    2. Duplicate endpoint height ([8, 3, 3, 8, 10]): Index 0 (8) pops the single 3 (visible = 1), then sees stack[-1] == 8 (visible = 2) and stops — never reaching 10 behind the second 8.

      • If you mistakenly wrote while stack and stack[-1] <= current_height: in Phase 1, i = 0 would pop both 3 and 8 (visible = 2), and then Phase 2 would see stack = [10] and add +1 for 10 (visible = 3) — wrong!

    Keeping Phase 1 strictly < current_height, counting stack[-1] once in Phase 2 when stack is non-empty, and popping stack[-1] when stack[-1] == current_height handles every duplicate pattern cleanly.

  6. Trace Example 1 step by step

    Walk through heights = [12, 5, 7, 9, 4, 15, 8] from i = 6 down to i = 0 (stack is written from bottom stack[0] to top stack[-1]):

      i | current_height | stack before   | popped (< h) | top >= h?       | visible | stack after
    ----+----------------+----------------+--------------+-----------------+---------+----------------
      6 |       8        | []             | none         | empty (no)      |    0    | [8]
      5 |      15        | [8]            | 8            | empty (no)      |    1    | [15]
      4 |       4        | [15]           | none         | 15 (+1)         |    1    | [15, 4]
      3 |       9        | [15, 4]        | 4            | 15 (+1)         |    2    | [15, 9]
      2 |       7        | [15, 9]        | none         | 9  (+1)         |    1    | [15, 9, 7]
      1 |       5        | [15, 9, 7]     | none         | 7  (+1)         |    1    | [15, 9, 7, 5]
      0 |      12        | [15, 9, 7, 5]  | 5, 7, 9      | 15 (+1)         |    4    | [15, 12]
    

    Reading visible_counts from index 0 to 6 gives [4, 1, 1, 2, 1, 1, 0], matching Example 1.

  7. Assemble the complete solution

    Even though there is a while loop nested inside the for loop, each of the n heights is pushed onto stack once and popped at most once, so the entire algorithm runs in O(n) time and O(n) space.

    from typing import List
    
    
    def count_visible_right(heights: List[int]) -> List[int]:
        """Return how many people to the right each person i can see."""
        n = len(heights)
        visible_counts = [0] * n
    
        # stack: heights forming the strictly rising "staircase" to the right of i,
        # stored from tallest/farthest at stack[0] down to shortest/nearest at stack[-1]
        # (for example, [15, 9, 7, 5] means 5 is immediately to the right, then 7, 9, 15).
        stack: List[int] = []
    
        # Sweep from right to left so when we stand at index i, the stack already
        # summarizes everyone visible from just in front of index i + 1.
        for i in range(n - 1, -1, -1):
            current_height = heights[i]
            visible = 0
    
            # Phase 1: pop everyone strictly shorter than person i.
            # Person i sees each of them, and person i is taller so nobody further
            # left will ever be able to see over person i to reach them.
            while stack and stack[-1] < current_height:
                stack.pop()
                visible += 1
    
            # Phase 2: if anyone remains on the stack, stack[-1] is the first person
            # to the right with height >= current_height. Person i sees this blocker,
            # and cannot see anyone standing behind them.
            if stack:
                visible += 1
    
                # Why pop on equality ('==')? Anyone further left looking past person i
                # has person i in between, and visibility requires strictly shorter ('<')
                # people in between—so an equal-height person behind i is completely hidden.
                if stack[-1] == current_height:
                    stack.pop()
    
            # Phase 3: push person i as the new nearest step of the staircase.
            stack.append(current_height)
            visible_counts[i] = visible
    
        return visible_counts
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine standing on a row of flat rooftops looking east toward the skyline. From your rooftop, you can see a rising staircase of shorter buildings in front of you — each one peeking out above the previous one — plus the very first building that reaches your eye level or higher, which then blocks everything behind it. Any small building tucked down in a valley behind a taller neighbor is invisible not just to you, but also to everyone standing west of that taller neighbor.

The naive approach stands at each index i and scans rightward one by one until hitting someone at least as tall as heights[i]. That fails on inputs that slope downward, like [100000, 99999, ..., 1], where nobody to the right is ever as tall as heights[i] — forcing every index to scan all the way to the end in O(n^2) time (roughly 5 billion comparisons for n = 100,000). Instead, we sweep right to left using a monotonic stack — a stack whose heights are kept strictly sorted (tallest at the bottom, shortest and closest at the top) — so once a shorter entry is hidden behind someone taller, it is popped once and never checked again.

Walk through Example 2 (heights = [8, 3, 3, 8, 10]) from right (i = 4) to left (i = 0):

i = 4 (h = 10): stack is []        -> sees 0. Push 10              -> stack = [10]
i = 3 (h =  8): 10 is not < 8      -> sees blocker 10 (+1). Push 8 -> stack = [10, 8]
i = 2 (h =  3): 8 is not < 3       -> sees blocker 8 (+1). Push 3  -> stack = [10, 8, 3]
i = 1 (h =  3): 3 == 3 (not < 3)   -> sees blocker 3 (+1), pop equal 3, push 3 -> stack = [10, 8, 3]
i = 0 (h =  8): pop 3 (+1), top 8 == 8 (+1), pop equal 8, push 8   -> sees 2, stack = [10, 8]

Answer: [2, 1, 1, 1, 0]

Complexity

  • Time: O(n). We iterate through the n indices once from right to left; although there is a while loop inside the for loop, each height is pushed onto stack once and popped at most once across the entire run, so total stack operations never exceed 2n.
  • Space: O(n). Returning visible_counts uses n integers, and stack holds at most n heights in the worst case (a strictly increasing array like [1, 2, 3, 4], where every step from right to left sees a taller neighbor and pushes without popping).

Edge cases

  • Single element ([7] -> [0]): the rightmost entry has nothing to its right, so stack starts empty and visible_counts[n - 1] is always 0.
  • Two elements ([3, 9], [9, 3], [4, 4] -> [1, 0]): adjacent neighbors have zero elements strictly between them, so heights[0] always observes heights[1] regardless of relative height.
  • All equal heights ([7, 7, 7, 7] -> [1, 1, 1, 0]): each entry observes its immediate neighbor of height 7, and popping the equal top ensures nobody sees two steps ahead.
  • Equal shorter heights between taller ends ([8, 3, 3, 8, 10] -> [2, 1, 1, 1, 0]): the leftmost 8 sees only the first 3 and the second 8, because the first 3 is not strictly shorter than the second 3 and the second 8 hides 10.
  • Strictly decreasing ([6, 4, 2] -> [1, 1, 0]): every entry is taller than everything to its right, yet sees only its immediate neighbor because that neighbor hides everyone shorter behind it.
  • Large height values (heights[i] up to 10^9): heights are only compared with < and == and never summed or multiplied, avoiding any integer overflow issues even in fixed-width languages.

Common mistakes

  • Forgetting to pop an equal-height blocker (stack[-1] == current_height). Variants with distinct heights never hit ties; when duplicates are allowed, leaving an equal height on the stack makes [8, 3, 3, 8, 10] keep both 3s on the stack and return 3 instead of 2 for index 0.
  • Changing the while condition from < to <= and still adding +1 when stack is non-empty. On [8, 3, 3, 8, 10], popping <= 8 at index 0 pops 3 and the blocking 8 (+2), and then adds +1 for 10 behind it, returning 3 instead of 2.
  • Counting only popped shorter elements and forgetting the taller/equal blocker. On [5, 7], 7 is not popped because 7 >= 5, yet 5 clearly sees 7; skipping the if stack: visible += 1 check returns 0 instead of 1.
  • Counting every shorter element to the right instead of only rising records. On [6, 4, 2], 2 is shorter than 6, but 4 stands in between (4 is not < min(6, 2)), so 6 cannot see 2.

Alternative approaches

  • Left-to-right monotonic stack: scan j from 0 to n - 1, keeping a stack of indices i whose rightward view has not yet been closed by someone >= heights[i] (strictly decreasing heights from bottom to top). For each new heights[j], pop every index with heights[stack[-1]] < heights[j] and increment its answer (j is visible to them and closes their view); then if stack is non-empty, increment visible_counts[stack[-1]] too (the nearest taller-or-equal entry on the left also sees j), pop stack[-1] if heights[stack[-1]] == heights[j], and push j. This achieves the exact same O(n) time and O(n) space, though accumulating each position's count across future iterations is slightly trickier to trace than computing visible_counts[i] all at once right-to-left.

Follow-up questions

  • How would you adapt this to count visible neighbors in both directions (left and right) for every index? Because the visibility condition heights[k] < min(heights[i], heights[j]) is completely symmetric between i and j, counting visible positions to the left is identical to running count_visible_right on the reversed list heights[::-1] and reversing that output back. Adding right_counts[i] + left_counts[i] element by element solves both directions in two clean O(n) passes (for [8, 3, 3, 8, 10], right is [2, 1, 1, 1, 0], left is [0, 1, 1, 2, 1], and total is [2, 2, 2, 3, 1]).
  • Across a row of n positions, what is the tightest upper bound on the total count of visible pairs? Every mutually visible pair (i, j) with i < j is counted once in sum(visible_counts). In our algorithm, visible only increases via stack.pop() (at most n - 1 pops total, since n items are pushed and at least heights[0] remains on the stack at the end) and via if stack: (at most n - 1 times, since i = n - 1 starts with an empty stack) — and at i = n - 2, stack holds just one element, so i = n - 2 cannot both pop an element and still find stack non-empty. Thus sum(visible_counts) <= 2n - 3 for any n >= 2 (0 for n = 1), reached for example on [9, 1, 2, 3, 9] (4 + 1 + 1 + 1 + 0 = 7 = 2 * 5 - 3).
  • What changes if you must return the exact indices visible from each position instead of only the count? Store indices j on stack instead of raw heights, comparing heights[stack[-1]] < current_height, and append each popped index (plus stack[-1] in Phase 2) onto visible_indices[i]. Because the total number of visible pairs across all n positions is linear (<= 2n - 3), building and returning all n index lists still takes O(n) total time and O(n) total memory!

Follow-up questions

Similar questions

More Ge interview questions

All 2 Ge questions →