Implementing Queue using Stacks with Java

🔥 Day 88 of #100DaysOfCode Today’s challenge: LeetCode: Implement Queue using Stacks 🔄📚 📌 Problem Summary Implement a queue (FIFO) using only stack operations: push(x) pop() peek() empty() You can only use standard stack operations (push, pop, peek, isEmpty). 🧠 Approach: Two Stacks Since: Stack → LIFO Queue → FIFO We reverse order twice using two stacks. ⚙️ Strategy Used: Move all elements from s1 → s2 Push new element into s1 Move everything back from s2 → s1 Now: The oldest element always stays on top of s1 pop() and peek() become O(1) 🔁 Core Idea Make push() costly Keep pop() and peek() fast ⏱ Time Complexity push() → O(n) pop() → O(1) peek() → O(1) empty() → O(1) 💾 Space Complexity: O(n) ⚡ Performance Runtime: 0 ms 100% faster 🚀 Memory: 42 MB 💡 What I Learned Stack and Queue can simulate each other with careful ordering. Order reversal is the key insight. Mastering these fundamentals strengthens problem-solving intuition. From Stack → Queue → Stack → Queue Data structure fundamentals getting sharper every day 💪 On to Day 89 🔥 #100DaysOfCode #LeetCode #Stack #Queue #Java #DSA #InterviewPrep

  • graphical user interface

To view or add a comment, sign in

Explore content categories