Data Structures & AlgorithmsVery hardProduct company OA

Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such pairs with a monotonic stack. What is printed?

Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such pairs with a monotonic stack. What is printed?
def see(h):
    st, pairs = [], 0
    for x in h:
        while st and st[-1] < x:
            st.pop(); pairs += 1
        if st: pairs += 1
        while st and st[-1] == x: st.pop()
        st.append(x)
    return pairs
print(see([4, 2, 3, 1, 5]), see([3, 1, 2, 2, 5]))
  1. A. 7 6
  2. B. 7 7
  3. C. 10 6
  4. D. 6 6

Correct answer: A. 7 6

Scanning left to right, x sees every shorter tower it pops (they are not blocked) plus the first tower left that is ≥ x, which then blocks everything further. Equal towers: x sees the equal one but nothing behind it, so equals are popped after counting. [4,2,3,1,5]: (4,2) (2,3) (4,3) (3,1) (1,5) (3,5) (4,5) = 7. [3,1,2,2,5]: (3,1) (1,2) (3,2) (2,2) (2,5) (3,5) = 6 – the first 2 cannot see 5 past the second 2. 10 counts all pairs.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic