Implement Stack using Queues in Java

🔥 Day 87 of #100DaysOfCode Today’s challenge: LeetCode: Implement Stack using Queues 📚🔁 📌 Problem Summary Implement a stack (LIFO) using only queue operations: push(x) pop() top() empty() You can only use standard queue operations (offer, poll, peek, isEmpty). 🧠 Approach: Two Queues Since stack is LIFO and queue is FIFO, we simulate stack behavior by rearranging elements during push. ⚙️ Strategy Used: Move all elements from q1 → q2 Add new element to q1 Move everything back from q2 → q1 Now: The newest element is always at the front of q1 pop() becomes simple → just q1.poll() 🔁 Key Idea Make push() costly Make pop() O(1) ⏱ Time Complexity push() → O(n) pop() → O(1) top() → O(1) empty() → O(1) 💾 Space Complexity: O(n) ⚡ Performance Runtime: 0 ms 100% faster than other submissions 🚀 💡 What I Learned Data structures can simulate each other. The trick is choosing where to handle the complexity. Understanding internal behavior matters more than memorizing code. Stack → Queue → Simulation mastery growing stronger 💪 On to Day 88 🔥 #100DaysOfCode #LeetCode #Stack #Queue #Java #DSA #InterviewPrep

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories