🚀 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
Monotonic Stack Solves LeetCode Daily Temperatures Problem in C++
More Relevant Posts
-
🚀 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 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 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 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 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
-
-
I stopped using Cursor earlier this year. Took me a while to understand why. It started gradually. I was running Claude Code inside Cursor's own terminal - using the IDE for smaller fixes, but doing the real work in the terminal pane. At some point I switched to iTerm2 and started running Claude Code there directly (now on Ghostty). I didn't make a decision to leave Cursor. I just forgot to open it. That's when I realized the shift. I wasn't editing files anymore. I was reviewing plans, spawning agents, checking their output, and redirecting when they drift. The unit of work went from "a function" to "a task." And when that changes, an IDE built around editing files with AI assistance starts to feel like overhead. I do miss the visual feedback - watching code change in real time. The extension ecosystem. But Claude Code has its own answers to these. MCP servers and CLI tooling replace most of what extensions did. Superset and Conductor give me a UI for diffs and running parallel agents. Different tradeoffs, not missing features. The real reason I can't go back is simpler: Cursor keeps you in the loop on every keystroke. Claude Code lets you operate a level up. Once you've made that shift, dropping back down feels like context-switching in the wrong direction. What was the moment your workflow changed? Or are you still in the IDE?
To view or add a comment, sign in
-
-
🚀 DSA Day 15: Divide and Conquer with Merge Sort! 🧩⚔️ After yesterday’s card-sorting logic, today I stepped up to one of the most powerful and reliable algorithms: Merge Sort. ✅ The Approach & Learning: 🔹 Divide & Conquer: Merge Sort recursively breaks the array into single-element pieces, then "merges" them back in perfect order. 📉📈 🔹 The Logic: I used a recursive strategy to split the data and two pointers to weave the halves together. It’s like breaking a big problem into tiny, easy-to-solve tasks. 🧵 📊 Complexity: Time: O(n log n) (Best, Average, and Worst Case! ⚡) Space: O(n) 💾 ⚠️ The Trade-off: Memory: Speed comes at a price! Merge Sort is not in-place, meaning it needs extra memory to store the sub-arrays it creates. Already Sorted? Unlike Insertion Sort, Merge Sort doesn't have an "early exit." It does the same amount of work even if the array is already perfect. It chooses consistency over shortcuts! 🔄 🎯 The Lesson: Sometimes you have to break everything apart to build it back better and faster. On to Day 16! ➡️ #Day15 #JavaScript #DSA #MergeSort #BigO #ProblemSolving #LearningInPublic #Algorithms #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 117 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After conquering Monotonic Stacks, today I tackled an interesting array and Hash Map problem on LeetCode: "Minimum Distance Between Three Equal Elements I" in C++. The Problem: Given an array, we need to find three identical elements at distinct indices (i, j, k) such that their "distance" abs(i - j) + abs(j - k) + abs(k - i) is minimized. If no such tuple exists, return -1. My Approach: Instead of a brute-force O(N^3) loop to find triplets, I optimized the solution using a Hash Map (unordered_map)! 🧠 The Logic: Math Simplification: The distance formula abs(i - j) + abs(j - k) + abs(k - i) actually simplifies to 2 \times (k - i) assuming i < j < k. This was the "Aha!" moment! I didn't even need the middle index j for the calculation, just the first and third indices of the triplet. Tracking Indices: I used a hash map where the key is the array element and the value is a vector storing all the indices where this element appears. On-the-Fly Calculation: As I iterate through the array, the moment a number appears for the third time (or more), I grab its current index (i3) and the index from two occurrences ago (i1). I calculate the distance as 2 times (i3 - i1) and update my minimum answer. Sliding Window Feel: By always checking the latest index (n-1) and the index two steps back (n-3), I ensure I'm always calculating the tightest possible distance for any three consecutive occurrences of a number. Takeaway: This problem is a great reminder of how mathematical simplification combined with Hash Maps can turn an intimidating problem into an elegant O(N) Time and Space complexity solution. Keep an eye out for those hidden formulas! ⚡ Keep pushing! 💻🔥 #Day117 #CPP #HashMap #Arrays #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices
To view or add a comment, sign in
-
-
🚀 Binary Search | Clean Thinking > Complex Code Just solved the classic Binary Search LeetCode Problem 704 with 100% test cases passing and optimal runtime. Here’s a structured breakdown of my approach 👇 🎯 Problem Goal Find the index of a target element in a sorted array using an efficient approach. 🧠 My Approach 1. Define the Search Space → Initialize low = 0, high = n - 1 2. Apply Binary Search Logic → Compute mid → Compare target with nums[mid] → Eliminate half of the search space each step 3. Maintain Clean Boundaries → Move low or high precisely to avoid infinite loops 4. Exit Condition → Return index if found → Else return -1 ⚡ What I Focused On • Writing minimal, readable code • Avoiding unnecessary conditions • Staying calm and methodical • Trusting fundamentals over shortcuts 💡 Key Takeaway Strong fundamentals + structured thinking = fast and reliable problem solving 📈 Outcome ✔️ 100% test cases passed ✔️ Optimal time complexity: O(log n) ✔️ Clean execution without overthinking Building this discipline every day. Small wins → Big growth 💪 #BinarySearch #DataStructures #ProblemSolving #LeetCode #CodingJourney #TechGrowth #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Day 40 – Staying Consistent 🚀 🧠 DSA – (Linked List): Reverse Linked List Detect Cycle ⚛️ Development: Pagination API Filtering + Sorting Backend 💻 Machine Coding: Data Table with Pagination + Sorting Now building interview-level features. #50DaysOfCode
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
Keep going 💪 ✨️ Jitesh Saini