🚀 DSA Consistency Challenge – Day 76 Today’s focus was on Greedy Validation + String Simulation, where the real challenge wasn’t coding… but thinking in the right direction 🧠⚡ 🔴 1️⃣ Check if a Parentheses String Can Be Valid (Medium) 💡 Problem Twist: You’re allowed to change some characters — so instead of building the exact string, the real question is: 👉 Is it even possible to make it valid? 🧠 Approaches: 🔹 Brute Force Try all combinations for unlocked positions Validate each string ⛔ Exponential → Not practical 🔹 Stack-Based Approach Use stack for '(' and another for flexible indices Try to match ')' with available '(' or flexible positions Finally match remaining '(' with flexible positions (order matters!) ⏱️ O(n) time | O(n) space 🔹 Greedy (Optimal 💯) ✨ Key Insight: Validate instead of constructing Left → Right: Assume unlocked can act as '(' → Avoid excess ) Right → Left: Assume unlocked can act as ')' → Avoid excess ( 🔥 If both passes are valid → answer is TRUE ⏱️ O(n) time | O(1) space 🔴 2️⃣ Remove All Occurrences of a Substring (Medium) 💡 Core Idea: Removing a substring can create new occurrences → requires careful simulation 🧠 Approaches: 🔹 Brute Force (Find + Erase) Keep removing leftmost occurrence using find() ⛔ Inefficient due to repeated scanning ⏱️ O(n²) 🔹 Stack / String Simulation (Efficient ✅) Build result string step-by-step After each character: Check last m characters If match → remove instantly ✨ Works like a hidden stack ⏱️ O(n * m) | 🧠 O(n) 💭 Key Takeaways: Greedy isn’t always about max/min — sometimes it’s about validating feasibility Bidirectional traversal can simplify constraint-heavy problems Many string problems secretly use stack patterns Optimization often comes from avoiding repeated work
Greedy Validation + String Simulation DSA Challenge
More Relevant Posts
-
𝗜𝗻𝘀𝘁𝗿𝘂𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗿𝗲 𝗮 𝘄𝗶𝘀𝗵. 𝗛𝗼𝗼𝗸𝘀 𝗮𝗿𝗲 𝗮 𝗴𝘂𝗮𝗿𝗮𝗻𝘁𝗲𝗲. 𝗖𝗟𝗔𝗨𝗗𝗘.𝗺𝗱 tells Claude what you'd like to happen. Hooks make sure it happens, every single time, whether the model remembers or not. That distinction is the entire point of the system. 𝗕𝗲𝗳𝗼𝗿𝗲: "Always run prettier after editing." Add to CLAUDE.md. Cross your fingers. 𝗔𝗳𝘁𝗲𝗿: A `PostToolUse` hook with matcher `Edit|Write` runs prettier on the file. The model can't skip it. 𝗕𝗲𝗳𝗼𝗿𝗲: "Don't touch the .env file." Pray. 𝗔𝗳𝘁𝗲𝗿: A `PreToolUse` hook exits with code 2. The edit is blocked, and your stderr message is fed back to Claude as the reason. 𝗕𝗲𝗳𝗼𝗿𝗲: "Re-inject project conventions after compaction." Hope the summary kept it. 𝗔𝗳𝘁𝗲𝗿: A `SessionStart` hook with the `compact` matcher echoes whatever you want straight back into context. 𝗕𝗲𝗳𝗼𝗿𝗲: "Notify me when you need input." Watch the terminal. 𝗔𝗳𝘁𝗲𝗿: A `Notification` hook fires `osascript`. Desktop banner. Alt-tab away with confidence. Underneath all four examples sits the same machinery. Hooks fire deterministically at lifecycle points. Exit code 0 lets the action through. Exit 2 blocks it and turns your stderr into model feedback. JSON output unlocks finer control — allow, deny, ask, or rewrite the tool's input mid-flight. Matchers and the new `if` field decide which calls a hook even spawns for. Anything you keep reminding the agent to do is probably a hook waiting to be written. What's the one rule you keep repeating that should just be a hook? #ClaudeCode #Anthropic #AIEngineering #DeveloperTools #DevProductivity #AICoding #AgenticCoding
To view or add a comment, sign in
-
🚀 Day 38 of #LeetCodeDailyChallenge Today’s problem was all about strings, pattern observation, and sequence generation 🔢⚡ 📌 Today’s Problem: Count and Say 📍 Topic: Strings / Recursion ⚡ Difficulty: Medium 💡 What I learned today: 🔹 Generating sequences based on previous outputs 🔹 Traversing strings and counting consecutive characters 🔹 Building new strings efficiently using iteration 🔹 Understanding recursive and iterative approaches 🔹 Improving observation skills for pattern-based problems At first, the sequence generation process felt confusing 😵💫 It was tricky to understand how each term is formed by “reading” the previous term carefully. But after breaking the string into groups of consecutive characters and counting them step by step, the logic became much clearer 💡 Problems like these really improve pattern recognition, string handling, and logical thinking 🚀 #DSA #LeetCode #Strings #Recursion #ProblemSolving #CodingJourney #LearningInPublic #Consistency #KeepGoing
To view or add a comment, sign in
-
🚀 Blind 75 Journey Update – Phase 3 Completed (Sliding Window) I’ve successfully completed Phase 2: Two Pointers, and now I’ve moved through one of the most important interview patterns in DSA: 🔹 Phase 3 – Sliding Window (Completed) Problems covered: 1️⃣1️⃣ Longest Substring Without Repeating Characters (3) 1️⃣2️⃣ Longest Repeating Character Replacement (424) 1️⃣3️⃣ Minimum Window Substring (76) 💡 What I learned in this phase: This phase strengthened my understanding of one of the most powerful optimization techniques in arrays & strings: • Dynamic window expansion and contraction • Frequency tracking using HashMap / arrays • Maintaining optimal subarray/subsequence constraints • Handling real-time updates efficiently • Converting brute-force O(n²) → optimized O(n) solutions 🧠 Key Insight Sliding Window is not just a pattern — it's a mindset: Instead of recomputing, reuse previous computation while expanding and shrinking intelligently. It’s heavily used in: String processing problems Subarray optimization Streaming / real-time data problems 🎯 My Focus Moving Forward I’m continuing the Blind 75 journey in strict chronological order, focusing on: ✔ Pattern understanding before memorization ✔ Writing approach before coding ✔ Improving time & space optimization intuition ✔ Building strong DSA fundamentals step by step 🚀 Next Phase Coming Up: 🔹 Continuing Blind 75 with next patterns (Stack / Binary Search / Linked List depending on order) Consistency over speed. Depth over shortcuts. #Blind75 #SlidingWindow #DataStructures #Algorithms #LeetCode #CodingJourney #SoftwareEngineering #ProblemSolving #BuildInPublic #InterviewPreparation
To view or add a comment, sign in
-
A clean way to solve LeetCode 76 — Minimum Window Substring — in O(N+M). Brute force tries every start-end pair, and for each window rescans the inside to check coverage. That's O(N²M) and you'll timeout immediately. There's a sharper move: maintain a live frequency map as you expand and shrink. Two counters — have and need — tell you in O(1) whether the window is valid: need = number of unique characters you must find in t have = how many of those unique characters you've actually satisfied in the current window A character is "satisfied" when its count in the window meets or exceeds its required count from t. The algorithm: Expand: slide the right pointer through s, adding each character to the window map. When a character just hits its required frequency, increment have. When have equals need, you've found a valid window. Now shrink. Shrink: while the window stays valid, record it if it's the smallest you've seen. Then move the left pointer inward to minimize. If shrinking removes something essential, have decrements and the window breaks. Go back to expanding, repeat until the end of s. Walked through the full algorithm visually on the example s="DAOBECODEBANCDNK", t="ABC" → answer="BANC". Visualizing the harder DSA problems I've worked through, one at a time. The sliding window pattern is foundational; once you lock it here, you can reuse it for longest substring without repeating, fruit into baskets, max consecutive ones, and dozens more. Full version (link in first comment). What's a pattern you wish was animated clearly? #dsa #algorithms #leetcode #softwareengineering #coding #slidingwindow #datastructures
To view or add a comment, sign in
-
Recently, while revising sliding window problems, one thing became very clear: Sliding window is less about “moving a window” and more about maintaining the right state efficiently. In many array and string problems, the brute-force approach recalculates information for every subarray or substring, which quickly becomes expensive. The interesting shift happens when we stop recomputing and instead maintain information as the window expands or shrinks. This pattern appears in problems like: • Longest Repeating Character Replacement • Longest Substring Without Repeating Characters • Binary Subarrays With Sum • Count Number of Nice Subarrays What I found interesting is that implementation is usually not the hard part. The actual challenge is identifying: “What information should stay valid while the window moves?” Sometimes it’s: • Frequency counts of characters • Count of valid elements in a range • A condition that tells us when to expand or shrink the window Takeaway: Many O(n²) problems become O(n) once we stop recalculating information and start maintaining the right state efficiently. #DSA #Algorithms #ProblemSolving #Coding 🧠
To view or add a comment, sign in
-
🏗️ 𝗧𝗵𝗲 𝗖𝗮𝘀𝘂𝗮𝗹 𝗕𝘂𝗶𝗹𝗱𝗲𝗿... 𝗗𝗼𝗲𝘀 𝗧𝗼𝗼𝗹 𝗰𝗵𝗼𝗶𝗰𝗲 𝗯𝗲𝗮𝘁 𝗠𝗼𝗱𝗲𝗹 𝗰𝗵𝗼𝗶𝗰𝗲? From what I am finding through my runs is that the agent's editing primitive matters more than the model you pick. When I used opencode's 𝗲𝗱𝗶𝘁 tool on multi-line function bodies, the model had to produce every replacement line inside a JSON string — no surrounding context, explicit indentation, no guardrails. Result: lines landing at column 0, syntax errors, panicked re-edits, and token count tripling. Switched to 𝘄𝗿𝗶𝘁𝗲 (full file regeneration). Same model, same endpoint — task completed cleanly. 📕The fix wasn't a bigger model. It was a better-shaped tool. I guess use 𝗲𝗱𝗶𝘁 for single-line renames. Use 𝘄𝗿𝗶𝘁𝗲 for anything touching a function body. The format has to match how LLMs naturally generate code. Keep in mind, I am hands-off when I run this and not through interactive sessions. These learnings could be part of the bigger topic of context engineering, where you become specific and tailored to the problem space. These small optimisations can or may go a long way, according to me. 🔗 Full lessons: https://lnkd.in/gjEtWEj5 #AIEngineering #CodingAgents #LLMs #BuildingInPublic
To view or add a comment, sign in
-
🚀 DSA Consistency Challenge – Day 74 💻🔥 Today’s problems focused on Greedy Thinking, Prefix/Suffix Optimization, and String Manipulation ⚡🧠 🔴 1️⃣ 1653. Minimum Deletions to Make String Balanced (Medium) 📌 Goal: Make the string balanced such that no 'b' appears before an 'a'. 🔹 Approach 1: Prefix & Suffix Count Count how many 'b' characters are present on the left side. Count how many 'a' characters are present on the right side. For every position, calculate: left_b + right_a This represents deletions needed if we split the string at that point. ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) 🔹 Approach 2: Optimized Prefix Counting Instead of storing both prefix and suffix arrays: Store only suffix count of 'a' Keep count of 'b' while traversing Minimize: b_on_left + a_on_right ✅ Same logic with better space optimization ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) 🔹 Approach 3: Stack + Greedy Traverse characters one by one. Whenever a 'b' comes before an 'a', remove the conflicting 'b'. Count deletions greedily during traversal. 💡 Key Observation: Every "ba" pair creates imbalance. ✅ Simple and intuitive approach ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) 🟢 2️⃣ 2553. Separate the Digits in an Array 📌 Goal: Separate all digits of each number while maintaining order. 🔹 Approach 1: String Conversion Convert each integer into a string. Traverse each character and push digits into result array. ✅ Clean and beginner-friendly ✅ Time Complexity: O(total digits) ✅ Space Complexity: O(1) (excluding output array) 🔹 Approach 2: Mathematical Extraction (Brute Force) Extract digits using % 10 Digits come in reverse order, so reverse them before adding. 💡 Uses pure mathematical operations without string conversion. ✅ Time Complexity: O(total digits) ✅ Space Complexity: O(total digits) for temporary storage 📚 Concepts Practiced Today: Greedy Algorithms Prefix/Suffix Technique Stack-Based Conflict Handling String Manipulation Digit Extraction Consistency is building confidence day by day 💪🚀
To view or add a comment, sign in
-
Day 38/50 of DSA Challenge Today’s problem introduced me to the concept of a Monotonic Stack combined with a greedy approach. • Remove K Digits Key Learning: To form the smallest possible number, we remove larger previous digits whenever a smaller digit appears and maintain an increasing stack order. Also worked on handling important edge cases like: 1. Leading zeros 2. Remaining k removals 3. Empty result cases This problem improved my understanding of how greedy algorithms work together with data structures. Initially, the logic felt tricky, but after debugging and dry running multiple examples, the pattern became much clearer. Definitely one of those problems that strengthens problem-solving intuition rather than just coding speed. Slowly getting more comfortable identifying patterns instead of forcing brute-force solutions #DSA #Leetcode #Stack
To view or add a comment, sign in
-
-
I begin my exploration of the #clanguage ctype functions with two of the most popular: toupper() and tolower(). These are also the only ctype functions that modify single characters. Bonus: I show one way to emulate these functions. Yes, it's the easy way. The hard way I do next week. https://lnkd.in/gsNAaw6e
To view or add a comment, sign in
-
Today I solved one of the most classic hard problems on LeetCode — Largest Rectangle in Histogram (#84). And honestly? The solution didn't come from watching a tutorial. It came from thinking. --- I started by just trying to understand the problem. A histogram. Bars standing side by side. Each bar has a width of 1 and a height. The question: what's the largest rectangle you can fit inside? My first instinct — for every bar, treat it as the height of a rectangle and expand left and right as long as the neighboring bars are >= that height. Simple. Logical. O(n²). Brute force. I coded it. It worked. --- Then I asked myself — where is the repetition? Every bar was scanning left and right from scratch. But if the next bar is taller, why scan again? The boundary hasn't changed. That's when it clicked — I need something that remembers previous bars and discards them the moment they become useless. Last in, first out. A stack. --- The insight: Maintain a monotonically increasing stack of indices. The moment a shorter bar arrives — every bar in the stack that's taller than it has found its right boundary. Pop them. Calculate their area. Move on. Every bar gets pushed once. Popped once. Total operations: 2N. Complexity: O(n). --- What I actually learned today wasn't the algorithm. It was the process. Brute force first → find the repetition → remove it. Every optimization in computer science follows this exact path. --- 500+ problems solved. Still learning. Still pushing. If you're on the same path — let's connect. #DSA #LeetCode #Algorithms #SoftwareEngineering #BuildInPublic #BackendEngineering
To view or add a comment, sign in