Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE

Problem: Implement a queue using two stacks and report the dequeued values.

Problem: Implement a queue using two stacks and report the dequeued values.
class Q:
    def __init__(self): self.inb, self.out = [], []
    def push(self, x): self.inb.append(x)
    def pop(self):
        if not self.out:
            while self.inb: self.out.append(self.inb.pop())
        return self.out.pop()
q = Q(); res = []
for x in (1, 2, 3): q.push(x)
res.append(q.pop()); q.push(4); res.append(q.pop()); res.append(q.pop()); res.append(q.pop())
print(res, q.inb, q.out)
What is printed?
  1. A. [1, 2, 3, 4] [] []
  2. B. [1, 2, 4, 3] [] []
  3. C. [3, 2, 1, 4] [] []
  4. D. [1, 2, 3, 4] [4] []

Correct answer: A. [1, 2, 3, 4] [] []

Elements move from the input stack to the output stack only when the output stack is empty, which reverses them into FIFO order. 4 waits in inb until 2 and 3 are gone, so order is preserved. Each element is moved at most once: O(1) amortised per operation.

More Coding Interview Problems questions

Exams that ask this topic