Data Structures & AlgorithmsVery hardProduct placement · Amazon/Microsoft

A min-stack keeps a second stack of running minimums. What is printed?

A min-stack keeps a second stack of running minimums. What is printed?
st, mn, out = [], [], []
for op in [8, "pop", 8, 8, "pop", 3, 5, 3]:
    if op == "pop":
        x = st.pop()
        if x == mn[-1]: mn.pop()
    else:
        st.append(op)
        if not mn or op <= mn[-1]: mn.append(op)
    out.append(mn[-1] if mn else None)
print(out)
  1. A. [8, 8, None, 8, 8, 3, 3, 3]
  2. B. [8, None, 8, 8, None, 3, 3, 3]
  3. C. [8, None, 8, 8, 3, 8, 3, 3]
  4. D. [8, None, 8, 8, 8, 3, 3, 3]

Correct answer: D. [8, None, 8, 8, 8, 3, 3, 3]

A value is pushed onto the min-stack when it is ≤ the current minimum; using < breaks when a duplicate minimum is popped. Output: [8, None, 8, 8, 8, 3, 3, 3].

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

Exams that ask this topic