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?- A. [1, 2, 3, 4] [] []
- B. [1, 2, 4, 3] [] []
- C. [3, 2, 1, 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
- Problem: Evaluate a basic calculator expression with +, −, parentheses and spaces. python def calc(s): res, num, sign, st = 0, 0, 1, []…
- Problem: Decode a string like 3[a2[c]] where k[...] repeats the bracket content k times. python def decode(s): st, cur, k = [], '', 0 for…
- Problem: For each element, find the next greater element in a circular array (−1 if none). python def ngecircular(a): n = len(a); res =…
- Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price. python def spans(p)…
- Problem: Return the k most frequent words, ties broken alphabetically. python from collections import Counter def topk(words, k): c =…
- Problem: Check whether two strings are isomorphic (characters map one-to-one consistently). python def iso(s, t): return len(set(s)) ==…