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 [7, 7, "pop", 3, "pop", 3, 3, "pop"]:
    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. [7, 7, 7, 3, 7, 3, 3, 3]
  2. B. [7, 7, None, 3, None, 3, 3, None]
  3. C. [7, 7, 3, 7, 7, 3, 3, 3]
  4. D. [7, 7, 7, 3, 3, 7, 3, 3]

Correct answer: A. [7, 7, 7, 3, 7, 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: [7, 7, 7, 3, 7, 3, 3, 3].

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

Exams that ask this topic