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?- A. [5, 1, 3, 1, 1, 0]
- B. [3, 1, 2, 1, 1, 0]
- C. [3, 1, 2, 1, 1, 1]
- 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
- Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days…
- Problem: A sorted list of ticket prices is searched with Python's bisect module. python from bisect import bisectleft, bisectright a =…
- Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key. python orders = [("ravi", 3), ("asha", 1)…
- Problem: A juice stall sells a ₹5 cup; customers pay with ₹5, ₹10 or ₹20 notes and the stall starts with no change. Decide whether every…
- Problem: Builds 1..100 are tested; every build from some version onward is broken. isbad() is expensive, so find the first bad build with…
- Problem: Sort values by increasing frequency; values with the same frequency go in decreasing order. python from collections import…