Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs.

Problem: Design a stack that returns its minimum in O(1). The implementation below stores pairs.
st = []
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, 2]:
    push(x)
pop(); a = get_min()
pop(); pop(); c = get_min()
print(a, c)
What is printed?
  1. A. 2 5
  2. B. 3 5
  3. C. 3 3
  4. D. 2 3

Correct answer: C. 3 3

Each entry remembers the minimum at the time it was pushed: (5,5), (3,3), (7,3), (3,3), (2,2). One pop leaves (3,3) on top → 3. Two more pops remove (3,3) and (7,3), leaving the first (3,3) → 3 again. Keeping only a single 'current minimum' variable would lose the old minimum after popping. Every operation is O(1).

More Coding Interview Problems questions

Exams that ask this topic