Implement a Queue using Stacks

Data Structures
Easy
Uber
26.2K views

Implement a First-In-First-Out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).

Why Interviewers Ask This

Interviewers at Uber ask this to evaluate your ability to translate abstract data structure concepts into practical implementations. They specifically test if you understand the fundamental differences between LIFO and FIFO behaviors. This question reveals your problem-solving depth, as it requires manipulating two limited structures to simulate a third, demonstrating logical reasoning and mastery of time complexity trade-offs.

How to Answer This Question

1. Clarify Requirements: Immediately confirm that you must use exactly two stacks and support push, pop, peek, and empty operations. Ask about input constraints like null handling or maximum size. 2. Define Strategy: Propose a 'lazy' vs. 'eager' transfer approach. Explain that one stack handles incoming pushes while the second manages outgoing pops. Detail how moving elements from the first stack to the second reverses their order, achieving FIFO behavior. 3. Analyze Complexity: Discuss Time and Space complexity. Highlight that while individual operations might be O(n) in worst-case scenarios during transfer, the amortized cost is O(1). This shows you understand performance implications. 4. Walk Through Logic: Verbally trace a sequence of operations (push A, push B, pop) to demonstrate how elements move between stacks. Mention edge cases like popping from an empty queue. 5. Code Implementation: Write clean code with clear variable names, separating the logic for pushing onto the input stack versus transferring to the output stack only when necessary.

Key Points to Cover

  • Explicitly stating the amortized O(1) time complexity for pop/peek operations
  • Explaining the mechanics of reversing order via stack transfer clearly
  • Distinguishing between immediate transfer (eager) and deferred transfer (lazy) strategies
  • Handling edge cases where the queue transitions from full to empty
  • Demonstrating awareness of space complexity being linear relative to queue size

Sample Answer

To implement a queue using two stacks, I will use one stack for incoming elements and another for outgoing elements. Let's call them 'inputStack' and 'outputStack'. The core challenge is reversing the Last-In-First-Out nature of stacks to achieve First-In-First-Out for a queue. For the push operation, we simply add the new element to inputStack. This is always O(1). For pop and peek, the logic is slightly more complex. If outputStack has elements, we directly pop or peek from there because they are already in the correct reverse order. However, if outputStack is empty, we must transfer all elements from inputStack to outputStack. By popping everything from inputStack and pushing it onto outputStack, the oldest element becomes the top of outputStack. After this transfer, subsequent pops come from outputStack until it empties again. Regarding complexity, pushing is always O(1). Popping and peeking are O(1) on average due to amortization; although transferring takes O(n), each element moves from input to output exactly once over the lifetime of the queue. This ensures efficient performance even under heavy load, which aligns well with high-throughput systems like those at Uber. We also need to handle the empty check by verifying both stacks are empty. This approach balances simplicity with optimal time complexity.

Common Mistakes to Avoid

  • Attempting to solve the problem with only one stack, which makes FIFO impossible without extra arrays
  • Failing to mention amortized analysis, leading to incorrect claims of O(n) worst-case for every operation
  • Transferring elements on every push instead of only when the output stack is empty, causing unnecessary overhead
  • Ignoring the empty state check, resulting in runtime errors when attempting to pop from a completely empty queue

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 154 Data Structures questionsBrowse all 57 Uber questions