🚀 Day 115 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After diving into custom stacks yesterday, today I explored how to use them to mimic entirely different data structures! I tackled LeetCode's "Implement Queue using Stacks" (Easy) in C++. The Problem: We need to design a custom Queue (which follows First-In-First-Out / FIFO) using strictly standard Stack operations (which follow Last-In-First-Out / LIFO). My Approach: How do you reverse the behavior of a LIFO structure to act like a FIFO one? The secret lies in a classic Two-Stack approach! 🧠 The Logic: Two Stacks: I used an input stack (s1) to collect incoming data, and an output stack (s2) to serve the data out. Push Operation: Whenever a new element arrives, I simply push it onto s1. Super fast and straightforward! Pop & Peek Operations: Here is where the magic happens! To get the front of the queue, we actually need the bottom element of s1. So, whenever s2 is empty, I run a while loop to pop everything out of s1 and push it straight into s2. This completely reverses the order! Now, the top of s2 perfectly represents the front of our queue. Empty: The queue is fully empty only when both s1 and s2 have zero elements. Takeaway: This problem is a brilliant lesson in Amortized Time Complexity. Moving elements from one stack to another takes O(N) time, but because we only do this heavy lifting when s2 is completely empty, the average time complexity across multiple pop or peek calls effectively drops to O(1). A clever trick to move elements only when absolutely necessary! ⚡ Keep pushing! 💻🔥 #Day115 #CPP #Stack #Queue #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services LeetCode
Implement Queue using Stacks in C++
More Relevant Posts
-
🚀 Day 116 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After mastering queue implementations yesterday, today I leveled up by diving into the world of Monotonic Stacks! I tackled a classic LeetCode Medium problem: "Daily Temperatures" in C++. The Problem: Given an array representing daily temperatures, we need to figure out exactly how many days we have to wait after each day to get a warmer temperature. If there's no warmer day in the future, we just return 0. My Approach: At first glance, you might think of using a nested loop to check every future day, but that would give us a slow O(N²) time complexity. How do we do this efficiently in a single pass? The answer: A Monotonic Decreasing Stack! 🧠 The Logic: Storing Indices: Instead of storing the actual temperatures in the stack, I stored their indices. This is the golden trick because we need the index to calculate the number of days we waited! Iterating & Comparing: As I iterate through the array, I constantly check if the current day's temperature is greater than the temperature of the day sitting at the top of the stack. Pop & Calculate: If it is warmer, bingo! We found a warmer day for that past element. I pop that previous day's index from the stack, calculate the difference in days (current_index - previous_index), and store that difference in my answer array. I keep popping as long as the current day is warmer than the stack's top. Push: Once all cooler past days are resolved, I push the current day's index onto the stack so it can wait for its own future warmer day. Takeaway: This problem is a textbook lesson in optimizing time complexity. Even though there's a while loop inside a for loop, every index is pushed onto the stack exactly once and popped at most once. This brings our overall Time Complexity down to a beautiful O(N)! A brilliant way to keep track of elements that are "waiting" for a specific condition. ⚡ Keep pushing! 💻🔥 #Day116 #CPP #Stack #MonotonicStack #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services LeetCode
To view or add a comment, sign in
-
-
🚀 Day 111 of My DSA Problem Solving Journey - The Grind Continues! 🎉 Keeping the Linked List momentum going strong! Today, I tackled another classic LeetCode Medium problem: "Rotate List" in C++. The Problem: Given the head of a linked list, rotate the list to the right by k places. My Approach: The brute-force way would be to move the last node to the front k times, but that's too slow. Instead, I used a length-calculation and list-breaking approach. The biggest "aha!" moment here is realizing that rotating a list of length N by N places leaves it completely unchanged. So, we only really need to rotate by k % N places! 🧠 The Logic: Find Length: First, I traversed the list to count the total number of nodes (count). If the list is empty or has only one node, we just return it. Optimize k: I updated k using the modulo operator (k = k % count). If k is exactly 0, no rotation is needed, so return the head. Locate the Break Point: The new tail of our rotated list will sit exactly at position count - k. I traversed a pointer (nt) to this exact spot. Break and Rewire: * The node right after our break point (nt->next) becomes our newHead. I severed the list by setting nt->next = NULL. Finally, I traversed from the newHead to the very last node of the new segment and connected its next pointer back to the original head. Takeaway: Math meets pointers! Using the modulo operator saves us from unnecessary loops and Time Limit Exceeded (TLE) errors. This problem is a great reminder that optimizing the mathematical logic before manipulating pointers can make your code significantly more efficient. Keep pushing! 💻🔥 #Day111 #CPP #LinkedList #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services LeetCode
To view or add a comment, sign in
-
-
🚀 Day 114 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After tackling some quick string manipulation yesterday, today I shifted gears to Stack data structures! I took on LeetCode's "Min Stack" (Medium) in C++. The Problem: We need to design a custom stack that supports the usual operations (push, pop, top) BUT with a catch—we also need to retrieve the minimum element in constant O(1) time! My Approach: The tricky part is figuring out how to get the minimum value instantly without scanning the entire stack. To achieve this, I used a classic Two-Stack Approach. 🧠 The Logic: Two Stacks: I initialized a main stack (st) to store all the elements and an auxiliary stack (minSt) specifically to keep track of the minimum values at any given point. Push Operation: When pushing a new value, it always goes into the main stack. If the minSt is empty, OR if the new value is less than or equal to the current minimum (the top element of minSt), I push it onto minSt as well. Pop Operation: When popping, I check if the element being removed from the main stack is exactly the same as the current minimum at the top of the auxiliary stack. If it matches, I pop it from both stacks! Otherwise, just pop from the main stack. Retrieving Min: Because of how we maintained the auxiliary stack, calling getMin() is as simple as returning the top value of minSt. Zero searching required! Takeaway: This problem is a brilliant example of a Space-Time Tradeoff. By sacrificing a little bit of memory to maintain a second stack, we successfully optimized our time complexity to a strict O(1) for every single operation! ⚡ Keep pushing! 💻🔥 #Day114 #CPP #Stack #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices
To view or add a comment, sign in
-
-
🚀 Day 112 of My DSA Problem Solving Journey - The Grind Continues! 🎉 The Linked List momentum is unstoppable! Today, I tackled a very tricky LeetCode Medium problem: "Delete Node in a Linked List" in C++. The Problem: We need to delete a specific node from a singly-linked list. The catch? We are only given access to that specific node, not the head of the list! My Approach: Usually, to delete a node, we traverse from the head to find the previous node and change its next pointer. Since we don't have access to the head, that standard traversal is impossible. The biggest "aha!" moment here is realizing we don't actually need to delete the physical memory of the given node. Instead, we can disguise our node as the next one, and delete the next one instead! 🧠 The Logic: Overwrite the Value: First, I copied the data from the next node into the current given node (node->val = node->next->val). Now, our node is a clone of the next one. Target the Next Node: I saved the next node in a temporary pointer (ListNode* temp = node->next) because that's the one we are actually going to remove from memory. Bypass & Rewire: I updated the current node's next pointer to skip the temporary node (node->next = temp->next). Free Memory: Finally, I used delete temp; to prevent any memory leaks. Takeaway: A great reminder to think outside the box! Sometimes, manipulating the data inside the structure is much more efficient than changing the structure itself. Achieved a clean O(1) Time and Space complexity solution without traversing the list at all. Keep pushing! 💻🔥 #Day112 #CPP #LinkedList #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services LeetCode
To view or add a comment, sign in
-
-
📌 Strengthening DSA Concepts through Problem Solving Recently, I worked on LeetCode 1530 – Number of Good Leaf Node Pairs At first glance, it looks like a simple tree problem… but the real challenge is efficiently counting valid leaf pairs within a given distance. 🔍 Problem Summary You’re given a binary tree and a distance value. 👉 A pair of leaf nodes is considered good if the shortest path between them is ≤ distance 👉 Goal: Count all such good pairs Naive Thinking → Store all leaf nodes → Calculate distance between every pair But this approach is inefficient: ❌ Time complexity becomes O(n²) ❌ Not scalable for larger trees Optimized Approach (DFS + Distance Tracking) Instead of comparing all pairs directly: 👉 We process the tree bottom-up (DFS) 👉 At each node, we track distances of leaf nodes in its subtree 👉 Then combine results from left & right subtree smartly 🔑 Key Idea 1️⃣ For each node, maintain an array → arr[i] = number of leaf nodes at distance i 2️⃣ If it's a leaf node → return array with distance = 1 3️⃣ For every node: Get left subtree distances Get right subtree distances 4️⃣ Count valid pairs: 👉 If i + j ≤ distance → it's a good pair 5️⃣ Update current node distances: 👉 Shift distances by +1 (moving up the tree) ⚙️ Core Logic ✔️ Combine left & right subtree results ✔️ Count valid pairs using nested loops ✔️ Propagate updated distances upward ⏱️ Complexity Time Complexity: O(n × d²) ✅ (Since distance ≤ 10, this is efficient) Space Complexity: O(h × d) ✅ 🚀 Takeaway This problem helped me understand: ✔️ How to use DFS beyond traversal ✔️ How to pass structured data (arrays) in recursion ✔️ How local computations can build a global answer Let’s keep learning and improving every day 💪 #LeetCode #BinaryTree #DFS #DSA #ProblemSolving #CodingJourney #InterviewPreparation
To view or add a comment, sign in
-
Moving Beyond Brute Force: Optimizing Sum of Distances 🚀 In software engineering, writing code that works is only the first step. Writing code that scales is where the real challenge lies. I recently tackled LeetCode 2615 (Sum of Distances), and it’s a perfect example of why understanding time complexity is crucial for a developer. The Problem: Given an array, for each element, calculate the sum of absolute differences ∣i−j∣ ∣i−j∣ for all other indices j j where the values are identical.The Developer’s Approach: 1️⃣ Identify the Bottleneck: A naive nested loop ( O(n2) O(n2 ) ) would attempt billions of operations for an input size of 105 105 , leading to a Time Limit Exceeded (TLE) error. We need an O(n) O(n) solution.2️⃣ Data Grouping: Use a HashMap to group indices of the same value. This narrows our focus only to relevant elements. 3️⃣ The Math Pivot (Prefix Sums): Instead of re-calculating distances for every index, we use mathematics. The total distance for any index can be split into: Left Side: (count_of_elements_on_left * current_index) - (sum_of_left_indices) Right Side: (sum_of_right_indices) - (count_of_elements_on_right * current_index) The Result: By maintaining a running prefix sum while iterating through the grouped indices, we transform a complex quadratic problem into a linear one. Key Takeaway: When you see "sum of absolute differences" in an array, think Prefix Sums. It’s one of the most powerful tools in a developer’s arsenal to turn inefficient logic into high-performance code. How do you approach optimization when you hit a performance wall? Let’s discuss in the comments! 💻✨ #SoftwareEngineering #Coding #Algorithms #Optimization #LeetCode #ProblemSolving #DeveloperMindset #CleanCode
To view or add a comment, sign in
-
Day#18 🚀 Solved: LeetCode 141 – Linked List Cycle | Fast & Slow Pointer Detecting cycles in a linked list is a classic problem — elegantly solved with two pointers: 👉 Must detect without modifying the list and ideally in O(1) space 🔹 Problem: Given the head of a singly linked list, determine if the list has a cycle. Return true if a cycle exists, else false Cannot modify the nodes 💡 Key Intuition – Fast & Slow Pointer (Floyd’s Tortoise & Hare) “Move one pointer twice as fast as the other. If a cycle exists, fast will eventually meet slow.” 🔄 Process: Initialize slow = head, fast = head Move slow 1 step at a time Move fast 2 steps at a time If fast meets slow → cycle exists If fast reaches null → no cycle 🔹 Pseudo Code: function hasCycle(head): slow = head fast = head while fast != null AND fast.next != null: slow = slow.next fast = fast.next.next if slow == fast: return true return false 🔍 Example: Input: 3 → 2 → 0 → -4 → back to 2 slow moves 1 step, fast moves 2 steps After a few iterations → slow = fast → cycle detected ✅ Input: 1 → 2 → 3 → null fast reaches null → no cycle ❌ 💡 Why this works: • Fast moves 2× → if there’s a cycle, it will eventually lap slow • Constant space → O(1) • Elegant and deterministic solution ⏱️ Complexity: • Time → O(n) ✅ • Space → O(1) ✅ 📌 Why Two Pointers? • Perfect for linked lists & sequences • Avoids extra memory like hash sets • Detects cycles in one pass 🧠 What I learned: • Fast & slow pointer technique is generalizable to other sequence problems (like Happy Numbers) • Key idea: difference in speeds ensures meeting inside cycles • Elegant solutions often combine simple pointers + math reasoning 🔁 Key takeaway: 👉 “Move fast, detect slow — cycles cannot hide.” #LeetCode #LinkedList #TwoPointers #Algorithms #DataStructures #SoftwareEngineering #CodingInterview #ProblemSolving #SDE
To view or add a comment, sign in
-
🚀 Day 118 of My DSA Problem Solving Journey - The Grind Continues! 🎉 Today, I tackled an interesting array problem on LeetCode: "Shortest Distance to Target String in a Circular Array" in C++. The Problem: We are given a 0-indexed circular string array (where the end of the array connects back to the beginning) and a target string. Starting from a given startIndex, we need to find the shortest distance to reach the target, moving one step at a time either forward or backward. If the target does not exist, we return -1. My Approach: Instead of overcomplicating things with BFS or graph traversals, I used a clean and efficient O(N) approach leveraging basic mathematics! 🧠 The Logic: Iterative Search: I looped through the entire array to find all occurrences of the target string (words[i] == target). Two Paths: In a circular array, there are always two ways to travel between any two indices: Direct Distance: The straightforward path, calculated as the absolute difference: abs(i - startIndex). Wrap-around Distance: The path going the opposite way around the circle, calculated by subtracting the direct distance from the array's total length: n - dist. Finding the Minimum: Every time the target is found, I calculate the minimum of these two paths using min(dist, n - dist) and update my global shortest distance variable. Edge Case Handling: If the loop finishes and the minimum distance remains at its initial maximum value (INT_MAX), it means the target was never found, so I simply return -1. Takeaway: Circular arrays can seem tricky at first, but mastering the "wrap-around" logic makes them incredibly straightforward. This approach keeps the time complexity at O(N) and space complexity at a highly optimized O(1). Always look for the simple math before jumping into complex data structures! ⚡ Keep pushing! 💻🔥 #Day118 #CPP #Arrays #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services
To view or add a comment, sign in
-
-
🚀 Restarting My DSA Journey - Day 5 Continuing my journey of practicing Data Structures & Algorithms on LeetCode to improve my problem-solving skills and stay consistent as a developer. Today I worked on LeetCode #55 - Jump Game. 🧩 Problem We are given an array where each element represents the maximum jump length we can make from that position. Starting from the first index, we need to determine whether it is possible to reach the last index. Example: Input: [2,3,1,1,4] Output: true From index 0, we can jump to index 1, and from there we can reach the last index. 🔹 Brute Force Idea A straightforward way to solve this problem is to try every possible jump from each position. For example, if the value at index i is 3, we can try jumping to: • i + 1 • i + 2 • i + 3 From each of these positions we again explore all possible jumps and check if any path reaches the last index. This approach is similar to exploring all possible paths using recursion or backtracking. ✔ Easy to understand ❌ Time Complexity: O(2ⁿ) in the worst case because many paths may be explored. This quickly becomes inefficient for larger arrays. 🔹 Better / Optimal Approach - Greedy Strategy Instead of exploring every possible jump, we can keep track of the farthest index we can reach while scanning the array. We maintain a variable: maxReach → the farthest index that can currently be reached. Logic: • Start from index 0. • If the current index i is greater than maxReach, it means that position is unreachable. • Otherwise, update the farthest reachable index using: maxReach = max(maxReach, i + nums[i]) This way we always know the maximum distance we can reach so far while traversing the array. If we can traverse the entire array without hitting an unreachable index, then reaching the last index is possible. ✔ Time Complexity: O(n) ✔ Space Complexity: O(1) 💡 Key Learning Sometimes a problem that looks like it requires exploring many possible paths can actually be solved using a greedy approach by simply tracking the farthest reachable position. Day 5 / 30 of improving my problem-solving consistency and sharing what I learn along the way. #LeetCode #DSA #CodingJourney #ProblemSolving #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 122 of My DSA Problem Solving Journey - Mastering Two Pointers🎉 Today, I tackled an interesting array problem on LeetCode: "Maximum Distance Between a Pair of Values". It’s a perfect example of how leveraging sorted data can optimize your code massively! The Challenge: Given two non-increasing arrays nums1 and nums2, find the maximum distance j - i such that i <= j and nums1[i] <= nums2[j]. The Insight: Since both arrays are sorted in descending order, a brute-force approach would be too slow. Instead, we can use the Two-Pointer technique to traverse both arrays efficiently without looking back. The Logic: We place pointer i on nums1 and j on nums2. If nums1[i] <= nums2[j]: We have a valid pair! We update our maximum distance and increment j to explore if we can stretch the distance even further. If nums1[i] > nums2[j]: The current value at i is too large. Since the arrays are non-increasing, moving j won't help. We must increment i to find a smaller value. Complexity: Time Complexity: O(N + M) - Each pointer traverses its respective array at most once. Space Complexity: O(1) - Pure pointer manipulation, no extra space used. It's amazing how optimizing with two pointers can make the code so clean and efficient. ⚡ Keep grinding! 💻🔥 #Day122 #CPP #TwoPointers #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #Efficiency REGex Software Services LeetCode
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