🔥 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
Implementing Queue using Stacks with Java
More Relevant Posts
-
🔥 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
To view or add a comment, sign in
-
-
🔥 Day 92 of #100DaysOfCode Today’s challenge: LeetCode – Search a 2D Matrix 🧩📊 📌 Problem Summary You are given a matrix where: Each row is sorted in ascending order The first element of each row is greater than the last element of the previous row 👉 This means the entire matrix behaves like a sorted 1D array. Goal: Return true if target exists, otherwise false. 🧠 Approach: Double Binary Search Instead of scanning row by row, we use Binary Search twice. Step 1️⃣: Find the Correct Row Binary search on rows: If target > last element of row → move down If target < first element of row → move up Otherwise → target must be inside this row Step 2️⃣: Binary Search Inside That Row 💡 Why This Works? Because: Rows are sorted Row ranges don’t overlap It behaves like a flattened sorted array. ⏱ Time Complexity: O(log m + log n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Beats 100% submissions Memory: Very efficient 🔥 🧠 Key Learning Whenever: Data looks 2D But ordering behaves like 1D 👉 Think Binary Search Optimization Stack → Sliding Window → Queue → Binary Search → Matrix Search Patterns are connecting now 💪 On to Day 93 🚀 #100DaysOfCode #LeetCode #BinarySearch #Matrix #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
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
-
-
🚀 #50DaysDSAChallenge | Day 48/50 🚀 🧩 Problem: Check if Array Is Sorted and Rotated 📍 Platform: LeetCode (Easy) 💻 Solution: https://lnkd.in/gGae9M96 💭 Problem Overview: Given an array nums, determine whether it was originally sorted in non-decreasing order and then rotated some number of times (including zero). Duplicates are allowed. 🛠️ Approach Used (Deviation Count): Traverse the array and count how many times the order decreases A “deviation” occurs when nums[i] > nums[i+1] Also check the circular condition: last element vs first element If deviations are more than 1, the array is not sorted & rotated ⚡ Why this approach? Rotation of a sorted array introduces at most one break in order Simple linear scan avoids unnecessary rotations or sorting Works even with duplicate values ⏱️ Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) 🔑 Key Learning: A rotated sorted array can be validated by counting order breaks, and circular comparisons are essential for rotation-based problems. ✅ Status: Solved (Optimal) #50DaysDSAChallenge #Day48 #LeetCode #Arrays #Rotation #Java #DSA #ProblemSolving
To view or add a comment, sign in
-
-
Day 26 of Daily DSA 🚀 Solved LeetCode 225: Implement Stack using Queues ✅ Problem: Implement a LIFO stack using only queue operations. Approach: Used two queues: main queue → stores elements in stack order helper queue → assists during push operation Key idea: Move all elements from main to helper Insert the new element into main Move all elements back from helper to main This ensures the latest pushed element stays at the front, allowing pop() and top() in constant time. ⏱ Complexity: • push() → O(n) • pop() → O(1) • top() → O(1) • empty() → O(1) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 42.54 MB (Beats 89.59%) A great problem to understand how one data structure can simulate another. #DSA #LeetCode #Java #DataStructures #CodingJourney #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 11/03/26 — Building the Backbone: Custom Stack Implementation Today was a test of resilience. Despite heavy rain and no electricity, I made sure to stay consistent by implementing a Stack from scratch. Even when power is low, the motivation to keep the streak alive is high! 🏗️ Designing a Custom Stack I built a functional Stack using an ArrayList as the underlying container. This structure follows the LIFO (Last-In-First-Out) principle, which is essential for everything from undo buttons to recursion management. The Logic: push(n): Appends an element to the end of the list, which serves as the "top" of the stack. pop(): Removes the element from the last index of the list if it's not empty. top(): Retrieves the value at the last index without removing it. isEmpty(): Checks if the internal list size is zero. Performance Metrics: Time Complexity: O(1) for push, pop, and top operations (average case for ArrayList). Space Complexity: O(N) where N is the number of elements stored. 📊 Implementation Highlights FeatureQueue (March 2nd)Stack (Today)LogicFIFO (First-In-First-Out)LIFO (Last-In-First-Out)ControlHead and Tail pointersSingle "Top" pointer (end of list)Use CaseBFS / BufferingDFS / Undo / Function Calls📈 Consistency Report Consistency isn't just about the days when everything goes right; it's about showing up when things go wrong. Today, even with a machine going down due to low power, completing this implementation reinforces the core principles of memory management I've been studying. Seeing the Stack logic I used iteratively for Trees on March 6th now built from the ground up is another major milestone. Huge thanks to Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the roadmap. Every bit of code counts toward mastery! My tested Stack implementation is saved (just in time)! 📄👇 #DSA #Java #CodingJourney #Stack #DataStructures #LIFO #Consistency #LearningInPublic #CTOBhaiya
To view or add a comment, sign in
-
-
🔥 Day 94 of #100DaysOfCode Today’s problem: LeetCode – Online Stock Span 📈 📌 Problem Summary Design a class StockSpanner that calculates the stock span for each new price. 👉 The span of a stock’s price today is the number of consecutive days (including today) the price was less than or equal to today’s price. Example input: [100, 80, 60, 70, 60, 75, 85] Output: [1, 1, 1, 2, 1, 4, 6] 🧠 Approach: Monotonic Stack (Decreasing Stack) This is another powerful Next Greater Element pattern, but optimized for streaming input. Instead of storing just prices, we store: {price, span} ⚙️ Core Logic (in next(price)): 1️⃣ Initialize span = 1 2️⃣ While stack is not empty AND top price ≤ current price: Add popped span to current span 3️⃣ Push {price, span} into stack 4️⃣ Return span 💡 Why Store Span Instead of Index? Because: It compresses previous smaller values into one value. Avoids recalculating spans repeatedly. Makes each element pushed & popped only once. ⏱ Time Complexity: O(n) amortized Each price is pushed once and popped once. 💾 Space Complexity: O(n) 🚀 Performance Runtime: 30 ms Beats ~72% Clean and optimal solution ✔️ 🧠 Pattern Insight Problems like: Daily Temperatures Next Greater Element Stock Span 👉 All use Monotonic Stack Stack mastery getting stronger 🔥 On to Day 95 🚀 #100DaysOfCode #LeetCode #MonotonicStack #StockSpan #Java #DSA #InterviewPrep
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 41 / 100 | Spiral Matrix II -Intuition: -The goal is to generate an n × n matrix filled with numbers from 1 to n^2 in spiral order. -Start from the top row, move right, then move down the right column, then move left across the bottom row, and finally move up the left column. -After completing one layer, shrink the boundaries and repeat the process until the matrix is filled. -Approach: O(n²) -Initialize an empty n × n matrix. -Maintain four boundaries: top, bottom, left, and right. -Start filling numbers from 1 to n^2. -Fill the top row from left -> right and move the top boundary down. -Fill the right column from top -> bottom and move the right boundary left. -Fill the bottom row from right ->left and move the bottom boundary up. -Fill the left column from bottom -> top and move the left boundary right. -Repeat the process until all elements are filled. -Complexity: Time Complexity: O(n²) Space Complexity: O(n²) #100DaysOfCode #Java #DSA #LeetCode #Matrix
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
-
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