Maximum Visible Buildings on a Skyline Strip
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests ability to use a monotonic stack to compute, for each building, how many previous buildings it "blocks" and find the building that maximally reduces the visible skyline count.
Maximum Visible Buildings on a Skyline Strip
You are given a row of buildings photographed from the side. Each building is represented by its integer height. Buildings are indexed left to right from 0 to n-1.
A building at index j is visible from the left if no building to its left has a height greater than or equal to j's height. In other words, building j is visible if and only if it is strictly taller than all buildings that appear before it (indices 0 through j-1). Building 0 is always visible.
A demolition candidate is a single building whose removal causes the greatest increase in the number of visible buildings. When a building is removed, the remaining buildings close the gap (i.e., their relative order is preserved) and visibility is recomputed from scratch on the resulting sequence.
Your task is to return a list [idx, gain] where:
idxis the 0-based index (in the original array) of the demolition candidate.gainis the increase in the number of visible buildings after removing that building.
Tie-breaking rules:
- If multiple buildings produce the same maximum gain, choose the one with the smallest index.
- If no removal increases the number of visible buildings (every building's removal results in the same or fewer visible buildings), return
[-1, 0].
How visibility works
Given heights [3, 1, 4, 2, 5]:
- Building 0 (h=3): always visible. Visible count so far: 1
- Building 1 (h=1): 3 ≥ 1, not visible.
- Building 2 (h=4): 4 > 3, visible.
- Building 3 (h=2): 4 ≥ 2, not visible.
- Building 4 (h=5): 5 > 4, visible.
Total visible: 3 (indices 0, 2, 4).
What "gain" means
If removing building i changes the visible count from V to V', then gain = V' - V. We want the building i that maximises this gain (with smallest-index tie-break).
Constraints
1 ≤ len(heights) ≤ 20001 ≤ heights[i] ≤ 10^6- All heights are positive integers.
- The answer index is always a valid index in the original array (or
-1if no gain is possible).
Examples
Example 1
Input: best_demolition_candidate([3, 1, 4, 2, 5])
Output: [-1, 0]
Example 2
Input: best_demolition_candidate([5, 5, 5, 5])
Output: [-1, 0]
Example 3
Input: best_demolition_candidate([1, 3, 2, 5, 4, 6])
Output: [-1, 0]
Hints
Hint 1
First compute the baseline visible count using a running maximum: building j is visible iff heights[j] > max(heights[0..j-1]).
Hint 2
For each building i, think about what changes when it is removed: only buildings that were previously blocked solely because of building i can become newly visible. A monotonic stack of indices (strictly decreasing heights) tracks exactly which buildings form the 'visibility frontier'.
Hint 3
For a building i on the visibility stack, the buildings it 'blocks' are those between i and the next taller building on the stack whose heights are strictly greater than the predecessor of i on the stack but ≤ heights[i]. Count these efficiently as you build the monotonic stack, then the gain for removing i equals that count minus the visibility status of i itself.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Visibility rule recap
Building j is visible if and only if heights[j] is strictly greater than every height before it, i.e., strictly greater than max(heights[0..j-1]). Building 0 is always visible.
Key insight: what can removing building i do?
When we remove building i, the visible count can only increase if i was itself on the "visibility frontier" (i.e., it was visible and it was blocking some subsequent buildings). More precisely:
- If
iwas not visible itself, its removal cannot help any building to the right (they were already unblocked or blocked by something taller/equal that remains). In fact it can sometimes hurt if buildingiwas the only element keeping the running max at a certain level — but for positive-height sequences of the constraints given here, a non-visible building never changes the running max, so its removal is neutral. - If
iwas visible, its removal may reveal buildings to its right that had heights in the range(prev_max, heights[i]], whereprev_maxis the running max just before buildingi.
Monotonic stack structure
We maintain a strictly decreasing monotonic stack of (height, index) pairs as we scan left to right. Each element on the stack is a visible building. For each position j we can immediately tell:
- Whether
jis visible (its height exceeds the current stack top's height). - The "shadow interval" cast by each visible building
i: it blocks all subsequent buildings with heights in(prev_stack_height, heights[i]]until the next taller visible building.
For each visible building i at stack position k (with predecessor height p), the number of buildings it blocks equals the count of buildings between i and the next visible building taller than i whose heights are in the range (p, heights[i]]. Removing i makes those blocked buildings visible, but we lose i itself (it was visible). So gain(i) = blocked_count - 1.
For non-visible buildings, gain = 0 (or negative).
Complexity
- O(n) monotonic stack pass to compute gains for all visible buildings.
- O(n) overall time, O(n) space for the stack and auxiliary arrays.
The reference implementation uses an equivalent O(n²) brute-force for clarity (n ≤ 2 000 makes this fast enough), but the monotonic stack is the intended technique and runs in O(n).
Tie-breaking
We track best_gain and best_idx, updating only when gain > best_gain or when equal and i < best_idx.
Correctness argument
For every index i we compute the exact visible count after removal. The baseline and per-removal counts are correct by the definition of the running-maximum visibility rule. The final answer is therefore exactly correct.
from typing import List
def best_demolition_candidate(heights: List[int]) -> List[int]:
n = len(heights)
if n == 0:
return [-1, 0]
def count_visible(seq):
if not seq:
return 0
vis = 1
run_max = seq[0]
for h in seq[1:]:
if h > run_max:
vis += 1
run_max = h
return vis
baseline = count_visible(heights)
best_idx = -1
best_gain = 0
for i in range(n):
seq = heights[:i] + heights[i+1:]
v = count_visible(seq)
gain = v - baseline
if gain > best_gain or (gain == best_gain and gain > 0 and i < best_idx):
best_gain = gain
best_idx = i
if best_gain <= 0:
return [-1, 0]
return [best_idx, best_gain]