🔥 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
Implement Stack using Queues in Java
More Relevant Posts
-
Day 17/100 – LeetCode Challenge Problem Solved: Spiral Matrix Today’s problem required traversing a matrix in spiral order, starting from the top-left corner and moving right, down, left, and up repeatedly until all elements are visited. The key idea is to maintain four boundaries that represent the current layer of the matrix being processed: top, bottom, left, and right. We move in four directions step by step: ->Traverse from left to right across the top row. ->Traverse from top to bottom along the right column. ->Traverse from right to left across the bottom row. ->Traverse from bottom to top along the left column. After completing each direction, the corresponding boundary is adjusted inward so the traversal continues with the inner layer of the matrix. This process continues until the boundaries cross, ensuring every element is visited exactly once. Time Complexity: O(m × n) Space Complexity: O(1) (excluding the result list) Performance: Runtime 0 ms Key takeaway: Many matrix traversal problems become manageable when you define clear boundaries and shrink them step by step. Day 17 completed. Continuing the journey of strengthening algorithmic thinking through consistent practice. #100DaysOfLeetCode #Java #Algorithms #MatrixTraversal #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🔥 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
To view or add a comment, sign in
-
-
Day 77 - LeetCode Journey Solved LeetCode 82: Remove Duplicates from Sorted List II (Medium) today — a more advanced version of the duplicate removal problem. Unlike the basic version, here we need to remove all nodes that have duplicates, leaving only distinct values. 💡 Core Idea: Use a dummy node + two pointers approach. • A dummy node helps handle edge cases (like duplicates at the head) • Use prev to track the last confirmed unique node • Use curr to traverse the list When duplicates are found: → Skip all nodes with that value → Connect prev.next to the next distinct node If no duplicate: → Simply move prev forward ⚡ Key Learning Points: • Importance of a dummy node in linked list problems • Handling edge cases at the head • Removing elements completely (not just skipping extras) • Clean pointer manipulation with O(n) time and O(1) space This problem highlights the difference between: Keeping one copy (Easy version) Removing all duplicates (Medium version) That small change makes the logic significantly more interesting. ✅ Stronger understanding of pointer control ✅ Better handling of edge cases ✅ Improved problem-solving depth in linked lists These variations are where real learning happens 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 521 of #750DaysOfCode 🚀 🔎 1582. Special Positions in a Binary Matrix (LeetCode - Easy) Today I solved a simple yet interesting matrix traversal problem. 🧠 Problem Summary We are given an m × n binary matrix. A position (i, j) is called special if: ✔ mat[i][j] == 1 ✔ All other elements in row i are 0 ✔ All other elements in column j are 0 Our task is to count how many such special positions exist. 💡 Key Idea Instead of checking the entire row and column every time, we can: 1️⃣ Count the number of 1s in every row 2️⃣ Count the number of 1s in every column Then a cell (i, j) is special if: mat[i][j] == 1 rowCount[i] == 1 colCount[j] == 1 ⏱ Time Complexity O(m × n) We traverse the matrix twice. 🧩 What I Learned ✔ Efficiently using row and column counting ✔ Simplifying matrix conditions with precomputation ✔ Writing cleaner solutions for matrix-based problems Step by step progress every day. Consistency is the real key. 🚀 #LeetCode #Java #MatrixProblems #ProblemSolving #DataStructures #CodingJourney #750DaysOfCode #Day521
To view or add a comment, sign in
-
-
🔥Day 26 of #75DaysofLeetCode Cracked LeetCode 394 – Decode String (Medium) Today I solved a classic stack-based problem that really tests your understanding of nested structures! 💡 Problem Summary: Given an encoded string like 3[a2[c]], decode it. 👉 Output: accaccacc 🧠 Key Insight: Whenever you see nested brackets, think STACK. Because decoding happens inside-out ⤵️ a2[c] → acc → then 3[acc] → accaccacc ⚙️ Approach: ✔ Use two stacks: One for numbers (repeat counts) One for strings ✔ Traverse the string: Digit → build number [ → push current state ] → pop & decode Character → append 🚀 What I Learned: Stack is powerful for nested problems Always reset variables after pushing to stack Handle multi-digit numbers carefully (like 12[a]) ⏱️ Complexity: Time: O(n) Space: O(n) 📌 Takeaway: If the problem involves nested patterns → think stack immediately! #LeetCode #DSA #Java #CodingInterview #Stack #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Day 79 - LeetCode Journey 🚀 Solved LeetCode 203: Remove Linked List Elements (Easy) — a deceptively simple problem that strengthens core linked list fundamentals. At first, it feels like just removing nodes with a given value. But the real challenge lies in handling edge cases cleanly, especially when deletions happen at the head or consecutively. 💡 Core Idea (Dummy Node + Pointer Control): Introduce a dummy node pointing to head Use a pointer (prev) to traverse the list If prev.next.val == target, skip the node Otherwise, move the pointer forward This ensures safe deletion without losing track of the list. 🤯 Why it works? Because the dummy node acts as a stable anchor, allowing uniform handling of all cases — including when the head itself needs to be removed. ⚡ Key Learning Points: • Importance of dummy node in linked list problems • Handling edge cases like head deletion • Managing consecutive deletions efficiently • Clean pointer manipulation without breaking links • Achieving O(n) time and O(1) space This problem builds the foundation for many advanced linked list operations. Also, this pattern connects with: <>Remove Nth Node from End <>Delete Node in Linked List <>Remove Duplicates (I & II) <>Partition List ✅ Stronger understanding of pointer-based logic ✅ Better handling of tricky edge cases ✅ Writing clean and robust linked list code Mastering these basics is what makes complex problems easier later 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 36 of #100DaysOfLeetCode ✅ Solved: Plus One (LeetCode 66) Difficulty: Easy Status: Accepted (114/114 Testcases Passed) Runtime: 0 ms 💯 Today’s problem looked simple but reinforced an important concept — handling carry in arrays. 🧠 Problem Summary: We are given a large integer represented as an array of digits. We need to increment the number by one and return the updated array. 🔎 Key Insight: Start from the last digit (right to left): If digit < 9 → increment and return. If digit == 9 → set it to 0 and carry over. If all digits are 9 → create a new array with an extra digit at the beginning. 💡 Example: Input: [9,9,9] Output: [1,0,0,0] 🎯 What I Practiced Today: Reverse traversal of arrays Carry-forward logic Edge case handling (all 9s case) Writing optimized O(n) solution Even easy problems strengthen fundamentals when you focus on edge cases. Consistency > Complexity. 🔥 #Day36 #100DaysOfCode #LeetCode #Java #DataStructures #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 72 - LeetCode Journey Solved LeetCode 206: Reverse Linked List (Easy) today — one of the most fundamental problems for understanding linked list manipulation and pointer handling. The task is to reverse a singly linked list so that the direction of all pointers is flipped. 💡 Core Idea: Traverse the list once and reverse the pointer of each node. We maintain three pointers: • prev → previous node (initially null) • curr → current node being processed • next → stores the next node before changing links At each step: Save the next node Reverse the current node’s pointer Move both pointers forward This continues until we reach the end of the list. ⚡ Key Learning Points: • Understanding pointer manipulation in linked lists • Reversing links without extra space • Maintaining O(n) time complexity and O(1) space • Building a foundation for many advanced linked list problems This is a must-know pattern because it appears frequently in variations like: Reverse Linked List II Reverse Nodes in k-Group Palindrome Linked List ✅ Stronger understanding of linked list pointers ✅ Improved confidence with pointer manipulation ✅ Solid foundation for advanced linked list questions Small problems like this build the fundamentals of strong data structure skills 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
⚡ Day 4 — Merge Intervals (Greedy + Sorting) Consistency is slowly turning confusion into clarity. Today’s problem was Merge Intervals — a classic example where the real difficulty isn’t coding, but recognizing the pattern. 🧩 Problem solved: Merge Intervals 🔢 LeetCode: 56 At first glance, the problem looks messy because overlapping ranges create too many comparison possibilities. The turning point was realizing that trying to merge randomly is inefficient — sorting the intervals by start time simplifies everything. Once sorted, the logic becomes straightforward: • Compare the current interval with the last merged interval • If they overlap → extend the boundary • If they don’t → push a new interval No unnecessary comparisons. Just one clean pass. 🔍 Key learnings: • Sorting often converts complex interval problems into linear scans • Greedy decisions work when local choices don’t break global correctness • Tracking only the “last merged interval” avoids redundant checks • Pattern recognition matters more than code length Slowly building the instinct to see patterns before writing loops. Solutions are available here: https://lnkd.in/gW8atfqw More tomorrow. #DSA #Java #LeetCode #GreedyAlgorithm #CodingJourney #StudentDeveloper #LearningInPublic
To view or add a comment, sign in
-
-
Day 6 — this problem broke my brain until I thought about it like a chef cutting a sandwich. 🧠 LeetCode 241 — Different Ways to Add Parentheses The problem: Given an expression, return ALL possible results from every different way to place parentheses. 2-1-1 → [0, 2] — same numbers, different brackets, different answers. The insight 💡 Every operator is a potential "last operation." Split there. Solve left. Solve right. Combine every result from both sides. Repeat recursively for every operator. That's it. Divide and Conquer. "2*3-4*5" Split at * → left:"2", right:"3-4*5" Split at - → left:"2*3", right:"4*5" Split at * → left:"2*3-4", right:"5" ... combine all results → [-34,-14,-10,-10,10] Why recursion fits perfectly here: Smaller subexpressions have the same structure as the original. Classic D&C pattern — break, solve, merge. Real world connection 🔗 This is exactly how compilers build Abstract Syntax Trees. Every operator is a split point. Every subexpression becomes a subtree. Day 6 done. Streak alive. 💪 #DSA #LeetCode #Java #DivideAndConquer #Recursion #100DaysOfCode #BackendDeveloper #CompetitiveProgramming
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development