Question presented to candidate: "Implement a first-in, first-out queue in Python using only two stacks. Support push, pop, peek and empty, and tell me the time complexity of each operation."
What a strong answer should cover:
- An inbox stack for pushes and an outbox stack for pops and peeks; pour inbox into outbox only when the outbox is empty.
- Why pouring reverses the order so the oldest element is on top, and the invariant that pouring into a non-empty outbox would break.
- Amortised O(1) per operation (each element moves at most once), worst case O(n) for a single pop.
- The naive design that pours back after every pop is O(n) per pop.
- Python specifics: lists as stacks with
append/pop; in real codecollections.dequeis the queue to use, becauselist.pop(0)is O(n).
Clarifying questions expected:
- "What should pop do on an empty queue: raise or return a sentinel?"
- "Is amortised O(1) acceptable, or do you need a worst-case bound per call?"
Code / implementation expected: Yes โ a small Python class with two lists.