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) observes5,7,9, and15(4items):4at index4sits in a valley behind9, and8at index6sits behind15. - Index
1(5) observes7, which immediately blocks everything further right. - Index
2(7) observes9, which blocks everything further right. - Index
3(9) observes4and15(2items), while15blocks8. - Index
4(4) observes15, index5(15) observes8, and index6(8) has nothing to its right (0).
- Index
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: index0(8) observes index1(3) and index3(8), while index1hides index2(3) and index3hides index4(10). - Each of indices
1,2, and3observes only its immediate right neighbor, and index4observes0.
- Because intermediate elements must be strictly shorter (
Example 3
- Input:
heights = [6, 4, 2] - Output:
[1, 1, 0] - Explanation: In a strictly descending sequence, each element observes its immediate right neighbor (
6sees4;4sees2), which hides every smaller value behind it.
Constraints
1 <= len(heights) <= 100,0001 <= heights[i] <= 10^9
Step-by-step walkthrough
Understand the visibility rule visually
We are given a list
heightsofnentries arranged from left (0) to right (n - 1). For each indexi, we want to count how many indicesjto its right (j > i) have an unobstructed line of sight fromi.Index
ican observe indexjwhen every intermediate indexk(i < k < j) is strictly shorter than bothheights[i]andheights[j]:heights[k] < min(heights[i], heights[j]) for every k with i < k < jPicture Example 1,
heights = [12, 5, 7, 9, 4, 15, 8], as vertical bars while looking rightward from index0(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 9Notice two direct consequences of this rule:
- Immediate neighbors always see each other (when
j = i + 1, no indexklies strictly between them, so nothing can obstruct the view). - Ties block the view, because the inequality
heights[k] < min(...)is strict (<, not<=). In[8, 3, 3, 8, 10], the first3blocks index0(8) from seeing the second3, and the second8blocks index0from seeing10.
- Immediate neighbors always see each other (when
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 indexiand scan rightward (j = i + 1, i + 2, ...), trackingtallest_between— the tallest value encountered so far strictly betweeniandj:- Whenever
tallest_between < min(heights[i], heights[j]), indexisees indexj. - As soon as
heights[j] >= heights[i], stop scanning — indexjis at least as tall asiand 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_countsWhy 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 earlybreaknever triggers! Every indexiscans all the way ton - 1, doingn * (n - 1) / 2 ≈ 5 * 10^9loop iterations. We need anO(n)approach that avoids re-scanning the same suffix repeatedly.- Whenever
Key insight: visible elements form a strictly rising staircase
Look rightward from index
i(with heightcurrent_height = heights[i]). Every candidatej > ifalls into one of two cases:- Case 1:
heights[j]is shorter thancurrent_height. Heremin(current_height, heights[j]) = heights[j]. Thusiseesjif and only ifheights[j]is strictly taller than everything betweeniandj. Walking right fromi + 1, each visible shorter entry must set a new strict height record — forming an upward staircase (5 -> 7 -> 9in[12, 5, 7, 9, 4, 15, 8], skipping4because9already shadowed it). - Case 2:
heights[j]is at least as tall ascurrent_height. Heremin(current_height, heights[j]) = current_height. Indexisees only the very first position withheights[j] >= current_height(15in Example 1), and its view stops right there.
Notice what happened to
4(heights[4] = 4) in[12, 5, 7, 9, 4, 15, 8]: once9(heights[3] = 9) sits to the left of4, no index further left (i = 2, 1, 0) can ever see4! Anyone left of9has9standing in between, and9 > 4violatesheights[k] < min(heights[i], 4). Once4is shadowed by9, we can discard4permanently.- Case 1:
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 - 1down to0) 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], andstackcurrently holds the rising staircase to its right:[15, 9, 7, 5](stack[-1] = 5is closest to12):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!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]):-
Duplicate shorter values (
[8, 3, 3, ...]): From the first8(i = 0), index1(3) is visible, whereas index2(3) is hidden because index1in between is not< 3.- At
i = 1(current_height = 3), whenstackis[10, 8, 3],stack[-1]is3(not< 3), so Phase 1 pops0items. - Phase 2 sees
stackis non-empty (stack[-1] == 3 >= 3), sovisible += 1(the first3sees the adjacent3). - Critical rule: because
stack[-1] == current_height, we must pop that duplicate3before pushing the new3! Otherwisestackwould become[10, 8, 3, 3], and index0(8) would pop both3s and overcount.
- At
-
Duplicate endpoint height (
[8, 3, 3, 8, 10]): Index0(8) pops the single3(visible = 1), then seesstack[-1] == 8(visible = 2) and stops — never reaching10behind the second8.- If you mistakenly wrote
while stack and stack[-1] <= current_height:in Phase 1,i = 0would pop both3and8(visible = 2), and then Phase 2 would seestack = [10]and add+1for10(visible = 3) — wrong!
- If you mistakenly wrote
Keeping Phase 1 strictly
< current_height, countingstack[-1]once in Phase 2 whenstackis non-empty, and poppingstack[-1]whenstack[-1] == current_heighthandles every duplicate pattern cleanly.-
Trace Example 1 step by step
Walk through
heights = [12, 5, 7, 9, 4, 15, 8]fromi = 6down toi = 0(stackis written from bottomstack[0]to topstack[-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_countsfrom index0to6gives[4, 1, 1, 2, 1, 1, 0], matching Example 1.Assemble the complete solution
Even though there is a
whileloop nested inside theforloop, each of thenheights is pushed ontostackonce and popped at most once, so the entire algorithm runs inO(n)time andO(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
nindices once from right to left; although there is awhileloop inside theforloop, each height is pushed ontostackonce and popped at most once across the entire run, so total stack operations never exceed2n. - Space: O(n). Returning
visible_countsusesnintegers, andstackholds at mostnheights 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, sostackstarts empty andvisible_counts[n - 1]is always0. - Two elements (
[3, 9],[9, 3],[4, 4]->[1, 0]): adjacent neighbors have zero elements strictly between them, soheights[0]always observesheights[1]regardless of relative height. - All equal heights (
[7, 7, 7, 7]->[1, 1, 1, 0]): each entry observes its immediate neighbor of height7, 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 leftmost8sees only the first3and the second8, because the first3is not strictly shorter than the second3and the second8hides10. - 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 to10^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 both3s on the stack and return3instead of2for index0. - Changing the
whilecondition from<to<=and still adding+1whenstackis non-empty. On[8, 3, 3, 8, 10], popping<= 8at index0pops3and the blocking8(+2), and then adds+1for10behind it, returning3instead of2. - Counting only popped shorter elements and forgetting the taller/equal blocker. On
[5, 7],7is not popped because7 >= 5, yet5clearly sees7; skipping theif stack: visible += 1check returns0instead of1. - Counting every shorter element to the right instead of only rising records. On
[6, 4, 2],2is shorter than6, but4stands in between (4is not< min(6, 2)), so6cannot see2.
Alternative approaches
- Left-to-right monotonic stack: scan
jfrom0ton - 1, keeping a stack of indicesiwhose rightward view has not yet been closed by someone>= heights[i](strictly decreasing heights from bottom to top). For each newheights[j], pop every index withheights[stack[-1]] < heights[j]and increment its answer (jis visible to them and closes their view); then ifstackis non-empty, incrementvisible_counts[stack[-1]]too (the nearest taller-or-equal entry on the left also seesj), popstack[-1]ifheights[stack[-1]] == heights[j], and pushj. This achieves the exact sameO(n)time andO(n)space, though accumulating each position's count across future iterations is slightly trickier to trace than computingvisible_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 betweeniandj, counting visible positions to the left is identical to runningcount_visible_righton the reversed listheights[::-1]and reversing that output back. Addingright_counts[i] + left_counts[i]element by element solves both directions in two cleanO(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)withi < jis counted once insum(visible_counts). In our algorithm,visibleonly increases viastack.pop()(at mostn - 1pops total, sincenitems are pushed and at leastheights[0]remains on the stack at the end) and viaif stack:(at mostn - 1times, sincei = n - 1starts with an empty stack) — and ati = n - 2,stackholds just one element, soi = n - 2cannot both pop an element and still findstacknon-empty. Thussum(visible_counts) <= 2n - 3for anyn >= 2(0forn = 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
jonstackinstead of raw heights, comparingheights[stack[-1]] < current_height, and append each popped index (plusstack[-1]in Phase 2) ontovisible_indices[i]. Because the total number of visible pairs across allnpositions is linear (<= 2n - 3), building and returning allnindex lists still takesO(n)total time andO(n)total memory!
Follow-up questions
- How would you adapt this to count visible neighbors in both directions (left and right) for every index?
- Across a row of n positions, what is the tightest upper bound on the total count of visible pairs?
- What changes if you must return the exact indices visible from each position instead of only the count?
Similar questions
- Grid Hub Placement for Minimum Manhattan Distance
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One