Day 38: Efficiency through String Balancing! ⚖️ Problem 1653: Minimum Deletions to Make String Balanced Today’s challenge was to find the minimum deletions needed to ensure no 'b' comes before an 'a' in a string. It’s a classic problem that tests your ability to think about state transitions across a sequence. I implemented a prefix/suffix counting strategy. Instead of brute-forcing every deletion possibility, I pre-calculated the total count of 'a's and then iterated through the string while keeping a running count of 'b's. At each position, the sum of 'b's seen so far (to be deleted if they stay) and 'a's remaining (to be deleted if they appear later) gave me the cost to balance at that specific "split point." By tracking the minimum sum across all possible split points, I achieved a clean O(n) solution with just two passes. It’s a great reminder that sometimes "balancing" a problem is just about counting what’s on either side of the fence! #LeetCode #Java #StringAlgorithms #Optimization #CodingChallenge #ProblemSolving #Algorithms
Minimum Deletions to Balance String
More Relevant Posts
-
Two Pointers Pattern — Small Bug, Big Lesson :Today I worked on a classic string problem Reverse only the vowels in a string — without changing the positions of the other characters :Example "leetcode" → "leotcede" .Sounds simple — but I hit an important edge-case bug The Problem I Faced :I used the two-pointer approach one pointer from the left- one pointer from the right- move both until they hit vowels- swap- My logic worked… until it didn’t When the string had no vowels (or pointers crossed while searching), the program crashed with an out-of-bounds error Why? Because my inner loops kept moving the pointers without rechecking boundaries 💡 Key Lesson When using the Two Pointers pattern, if pointers move inside inner loops, you must also check boundary conditions there — not only in the main loop #Java #Algorithms #TwoPointers #ProblemSolving #LearningJourney
To view or add a comment, sign in
-
-
Day 65: The "One-Liner" Win 🎯 Problem 1784: Check if Binary String Has at Most One Segment of Ones Today was a lesson in simplifying logic. The challenge: check if a binary string contains more than one contiguous segment of '1's, given that the string starts with '1'. The Strategy: • Observation: If there are multiple segments of '1's, they must be separated by at least one '0'. • The Pattern: In a string starting with '1', any "new" segment of ones would look like "01" somewhere in the string. • The Execution: A simple !s.contains("01") handles the entire check. Sometimes we hunt for complex algorithms when a single string method is the ultimate counter. Clean, readable, and passed all test cases. 🚀 #LeetCode #Java #StringManipulation #Coding #Efficiency #DailyCode
To view or add a comment, sign in
-
-
Day 6/30 – LeetCode streak Today’s problem: Special Binary String This one finally felt like a proper "hard" — at first glance it’s just scary string juggling. What actually unlocked it for me was thinking of the string like balanced parentheses: - Treat '1' as "(" and '0' as ")". - Walk the string with a counter: '+1' on '1', '-1' on '0'. - Every time the counter comes back to '0', you’ve finished one smallest special chunk. Inside each such chunk, the outer '1' and '0' are basically fixed anchors. You strip them off, recursively make the inside as large as possible, then wrap it back as "1" + inner + "0". All those chunks go into a list, you sort them in descending order, then glue them together to get the lexicographically largest result. As for what felt hardest: Seeing those outer '1' and '0' as immovable anchors was the key. Once that clicked, recursion and "sort bigger chunks first" felt natural; before that, it just looked like raw string manipulation with no obvious starting point. #leetcode #dsa #java #recursion #consistency
To view or add a comment, sign in
-
-
🚀 Day 89 of #100DaysofLeetCode Problem: Minimum Size Subarray Sum Difficulty: Medium Today’s challenge was about finding the smallest length subarray whose sum is greater than or equal to a given target. Since all elements are positive, this problem is a perfect fit for the Sliding Window technique. Instead of checking all possible subarrays (which would be inefficient), I used two pointers: Expand the window by moving the right pointer and adding to the current sum. Once the sum becomes ≥ target, shrink the window from the left to find the minimum possible length. Keep updating the minimum length during this process. Key takeaways: Positive integers allow efficient window shrinking. Two pointers help reduce time complexity from O(n²) to O(n). Maintain a running sum and dynamically adjust window size. Return 0 if no valid subarray exists. Time Complexity: O(n) Space Complexity: O(1) Another solid sliding window problem completed 💪 #100DaysOfCode #100DaysOfLeetCode #LeetCode #DSA #SlidingWindow #TwoPointers #Java #ProblemSolving #CodingJourney #Algorithms
To view or add a comment, sign in
-
-
Day 12/30 – LeetCode streak Today’s problem: Number of Steps to Reduce a Number in Binary Representation to One Rules are simple: if the number is even, divide by 2; if it’s odd, add 1. But doing this by simulating the whole number each time is slow and messy. The trick is to walk the binary string from right to left and just count how many operations each bit contributes, while carrying a 1 when we “add 1”: - Ignore index 0 (most significant bit); we stop at 'i > 0'. - For each bit, compute 'bit = (s.charAt(i) - '0') + carry'. - If 'bit' is '1', it’s effectively odd → we need '+1' then '/2' → 'steps += 2' and set 'carry = 1'. - If 'bit' is '0' or '2', it’s even → just '/2' → 'steps += 1', 'carry' stays as is. - After the loop, if there’s still a carry, add one more step because we effectively turned something like '"111"' into '"1000"' and need one last divide to reach '1'. Day 12 takeaway: Instead of repeatedly mutating the number, counting how many times each bit causes “+1 then /2” vs “just /2” gives an O(n), no-conversion solution that feels much cleaner once the carry idea clicks. #leetcode #dsa #java #bitmanipulation #consistency
To view or add a comment, sign in
-
-
🔥 Day 513 of #750DaysofCode 🔥 LeetCode 1461 | Check If a String Contains All Binary Codes of Size K Today’s problem was a really interesting mix of strings + hashing + sliding window + bit manipulation. 🧠 Problem Summary: Given a binary string s and an integer k, return true if every possible binary code of length k exists as a substring of s. For example: Input: s = "00110110", k = 2 All possible binary codes of size 2 → "00", "01", "10", "11" Since all exist → ✅ true 💡 Key Insight For length k, total possible binary codes = 2^k So instead of generating all binary codes explicitly, we: Slide a window of size k across the string Store each substring in a HashSet If set.size() == 2^k, we return true ⚡ Optimized Thinking Since: k <= 20 2^20 = 1,048,576 We can also use: Rolling hash Bitmask technique Integer encoding instead of substring creation 🎯 What I Learned Today ✔ Instead of generating all combinations, track what appears ✔ Bitmasking can optimize substring problems ✔ Sliding window + hashing is powerful for pattern coverage problems ✔ Always check constraints before choosing brute force Consistency > Motivation 💪 Onwards to Day 514 🚀 #750DaysOfCode #LeetCode #Java #DSA #CodingJourney #BitManipulation #SlidingWindow
To view or add a comment, sign in
-
-
Day 20/30 – LeetCode streak Problem: Check if Binary String Has at Most One Segment of Ones A valid string can have ones only in a single continuous block, and the input has no leading zeros, so it always starts with '1'. Core idea Since 's' starts with '1', any second segment of ones must look like: '1...1 0...0 1...1' → which necessarily contains "01" at the point where ones restart. So if "01" appears anywhere, there are at least two segments of ones → return false. If "01" never appears, all ones are in a single prefix (possibly followed by zeros), so return true. This reduces to a single substring check in 'O(n)' time and 'O(1)' space. Day 20 takeaway: Instead of explicitly counting segments, spotting the forbidden pattern "01" turns the whole logic into a one-line string check that’s still fully correct and optimal. #leetcode #dsa #java #strings #consistency
To view or add a comment, sign in
-
-
Day 12/100 – LeetCode Challenge Problem Solved: Permutations Today’s problem was about generating all possible permutations of a given array of distinct integers. This is a classic backtracking problem where the objective is to build permutations step by step while ensuring each element is used exactly once in every arrangement. I implemented a recursive solution supported by a boolean array to track which elements were already included in the current permutation. At every recursive call, I select an unused element, add it to the current list, mark it as used, and continue exploring deeper. Once a permutation reaches the required length, it is added to the result set. Then comes the most important part — backtracking. I remove the last element and reset its state so other combinations can be explored. Time Complexity: O(n × n!) Space Complexity: O(n) excluding the output list #100DaysOfLeetCode #Java #Backtracking #Recursion #Algorithms #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 52/100 – LeetCode Challenge ✅ Problem: #1653 Minimum Deletions to Make String Balanced Difficulty: Medium Language: Java Approach: Greedy with Counter Time Complexity: O(n) Space Complexity: O(1) Key Insight: String must be of form aa...abb...b (all 'a's before 'b's). For each 'a' encountered after a 'b', we must delete either this 'a' or a previous 'b'. Greedily delete 'a' when it appears out of order. Solution Brief: Tracked count of 'b's seen so far. When encountering 'a': If no preceding 'b's, it's in correct position If there are preceding 'b's, delete this 'a' (increment result) and reduce 'b' counter Final result = minimum deletions needed. #LeetCode #Day52 #100DaysOfCode #Greedy #Java #Algorithm #CodingChallenge #ProblemSolving #StringBalance #MediumProblem #Counter #Optimization #DSA
To view or add a comment, sign in
-
-
🔥 Day 83 of #100DaysOfCode Today’s problem: LeetCode: Minimum Size Subarray Sum 🎯 📌 Problem Summary Given: An integer target An array nums Return the minimum length of a contiguous subarray whose sum is greater than or equal to target. If no such subarray exists → return 0. Example: target = 7 nums = [2,3,1,2,4,3] Output → 2 (because [4,3] = 7) 🧠 Approach: Sliding Window (Two Pointers) This is a classic variable-size sliding window problem. ⚙️ Strategy: Use two pointers: l (left) and r (right) Expand window by moving r Keep adding to total When total >= target: Update result Shrink window from left Subtract from total 🔁 Core Logic: for each r: total += nums[r] while total >= target: update min length total -= nums[l] l++ ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 💡 What I Learned Sliding window is extremely powerful for subarray problems. The key is knowing when to expand and when to shrink. Many medium/hard problems are just variations of this pattern. Today’s runtime: ⚡ 1ms (99% faster) Consistency builds mastery. On to Day 84 🚀 #100DaysOfCode #LeetCode #SlidingWindow #Java #DSA #InterviewPrep #CodingJourney
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