🚀 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
Min Stack Problem Solution in C++ with Two-Stack Approach
More Relevant Posts
-
🚀 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
-
-
🚀 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 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
To view or add a comment, sign in
-
-
🚀 Day 119 of My DSA Problem Solving Journey - The Grind Continues! 🎉 Today, I tackled an interesting array problem on LeetCode: "Split the Array" in C++. The Problem: We are given an even-length integer array. The goal is to split this array into two equal halves (nums1 and nums2) such that both arrays contain strictly distinct elements. If it's possible, we return true; otherwise, false. My Approach: Instead of sorting or using complex logic, I used an unordered_map to keep track of element frequencies. It's clean, efficient, and gets the job done perfectly! The Logic: Frequency Counting: I iterated through the entire array and stored the frequency of each number using the hash map. The Core Rule: For both nums1 and nums2 to have strictly distinct elements, a specific number can appear a maximum of two times in the entire array (one copy goes to nums1, and the other to nums2). Validation: I looped through the hash map. If any element's frequency is strictly greater than 2, it's impossible to distribute them without creating duplicates in one of the halves. In that case, I immediately return false. If the loop finishes without finding any frequency greater than 2, the split is totally possible, so I return true. Takeaway: Hash maps are incredibly powerful for tracking occurrences and solving frequency-based problems. This approach keeps the time complexity at an optimal O(N) and space complexity at O(N). Keep it simple and logical! ⚡ Keep pushing! 💻🔥 #Day119 #CPP #Arrays #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices
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
-
-
🚀 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
-
-
📌 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
-
🚀 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
-
-
Day 17. Sorting Logic & System Internals. Today’s progress: ✅ DSA — Implemented Selection Sort and Insertion Sort. Building functions to return sorted arrays from scratch is the best way to understand how different algorithms handle data movement and time complexity. CODE : https://lnkd.in/dTMCJdkq ✅ Operating Systems — Deep dive into Processes vs. Threads. Understanding execution units and memory sharing is a game-changer for writing efficient code. ✅ System Clean-up — Learned about Zombie and Orphan processes. It’s fascinating (and vital) to see how the OS manages "lost" processes and keeps the system from leaking resources. 17 days down. The fundamentals are stacking up. See you at Day 18. 🚀 #DSA #100DaysOfCode #BuildInPublic #OperatingSystems #ComputerScience #WebDev #DevJourney #SoftwareEngineering
To view or add a comment, sign in
-
Day 16/50 – DSA Challenge Today was about designing something smarter, not just solving. ->Min Stack This problem looks simple… until you realize: “getMin() must be O(1)” That’s where the real thinking starts. What I learned today: • Using an extra stack to track minimums is a design decision, not just coding • Every push/pop must maintain consistency between two stacks • This problem is less about loops and more about data structure design Key Insight: Good programmers solve problems. Better programmers design systems that make problems easier. ⚙️ From brute force → optimized → now smart data structure design That’s real progress. #DSA #LeetCode #DataStructures #CodingJourney #KeepLearning
To view or add a comment, sign in
-
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
Keep going 💪 ✨️ Jitesh Saini