Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs.

Problem: A min-stack supports push, pop, top and getMin in O(1) by storing (value, current minimum) pairs.
st, out = [], []
def push(x): st.append((x, min(x, st[-1][1]) if st else x))
def pop(): st.pop()
def get_min(): return st[-1][1]
for x in [5, 3, 7, 3, 8]: push(x)
out.append(get_min()); pop(); pop(); out.append(get_min()); pop(); out.append(get_min())
print(out)
What is printed?
  1. A. [3, 3, 5]
  2. B. [3, 3, 3]
  3. C. [3, 5, 5]
  4. D. [3, 7, 5]

Correct answer: B. [3, 3, 3]

Each entry remembers the minimum at the time it was pushed: (5,5), (3,3), (7,3), (3,3), (8,3). After popping 8 and 3 the top is (7,3) → 3; after popping 7 the top is (3,3) → 3. Duplicated minima (two 3s) are handled automatically.

More Coding Interview Problems questions

Exams that ask this topic