Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is shorter than both. For each person count how many they can see, using a monotonic stack from the right.

Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is shorter than both. For each person count how many they can see, using a monotonic stack from the right.
def visible(h):
    n = len(h); res = [0] * n; st = []
    for i in range(n - 1, -1, -1):
        cnt = 0
        while st and st[-1] < h[i]:
            st.pop(); cnt += 1
        res[i] = cnt + (1 if st else 0)
        st.append(h[i])
    return res
print(visible([8, 3, 5, 1, 7, 4]))
What is printed?
  1. A. [5, 1, 3, 1, 1, 0]
  2. B. [3, 1, 2, 1, 1, 0]
  3. C. [3, 1, 2, 1, 1, 1]
  4. D. [2, 1, 2, 1, 1, 0]

Correct answer: B. [3, 1, 2, 1, 1, 0]

Every shorter person popped by i is visible to i (nothing taller stands between); the first taller person left on the stack is also visible, and blocks everyone beyond. 8 sees 3, 5, 7 (1 is hidden by 5, 4 by 7) → 3; 5 sees 1 and 7 → 2. Counting everyone shorter to the right (5 for the first person) ignores blocking. Each height is pushed and popped once: O(n).

More Coding Interview Problems questions

Exams that ask this topic