Data Structures & AlgorithmsVery hardFlipkart/Uber OA · placement

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

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

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

Exams that ask this topic