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]))- A. 7 6
- B. 7 7
- C. 10 6
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros…
- Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign…
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…