Day 44: Avoiding the O(n²) Trap 🔍 Problem 3714: Longest Balanced Substring II Today’s goal: find the longest substring where all present characters appear equally. Since we only had 'a', 'b', and 'c' to deal with, I split the logic into three cases (1, 2, or 3 unique characters). Pro tip: I almost nuked my runtime by using map.clear() inside a loop. Since clear() iterates over the map to nullify entries, it’s O(n). Switching to new HashMap<>() kept the complexity at a clean O(1) reset and a total O(n) pass. Don't let built-in methods turn your linear solution into a nested nightmare. Complexity matters. 🧗♂️ #LeetCode #Java #CodingChallenge #ProblemSolving
Longest Balanced Substring in Java: Avoiding O(n²) Complexity
More Relevant Posts
-
Day 47: Flipping bits and taking names! 🔄 Problem 190: Reverse Bits Today's challenge was to reverse the bits of a 32-bit unsigned integer. While there are elite bit-manipulation tricks for this, I decided to trust my own logic first. The Game Plan: 1. Convert the integer to a binary string. 2. Reverse the string using StringBuilder. 3. Manually pad the trailing zeros to ensure it stays a full 32-bit representation. 4. Parse it back to an integer. Is it the most optimal O(1) bitwise solution? Not yet. But implementing your own logic before peaking at the "perfect" solution is how you actually learn. I'm hitting the books now to master the bit-shift approach for the next round. 🧗♂️ #LeetCode #Java #BitManipulation #Algorithms #CodingChallenge #ProblemSolving
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 48: Checking the time with Bit Manipulation! ⌚ Problem 401: Binary Watch Today’s problem involved a watch that represents hours and minutes using binary LEDs. The task was to find all possible times given a specific number of "on" LEDs. Instead of overcomplicating the combinations, I went with a clean brute-force approach across all possible hours (0-11) and minutes (0-59). The MVP of today’s code was Integer.bitCount(), which effortlessly counts the number of set bits (1s) in an integer. By checking if the combined bit count of the hour and minute matched the target, I could format and add the valid times to my result list. It’s O(1) effectively, given the fixed constraints of a clock, and way more readable than manual bit shifting. #LeetCode #Java #BitManipulation #Algorithms #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
Day 82/100 – LeetCode Challenge ✅ Problem: #43 Multiply Strings Difficulty: Medium Language: Java Approach: Manual Multiplication with Result Array Time Complexity: O(n × m) Space Complexity: O(n + m) Key Insight: Multiply digits from right to left (least significant first). Store intermediate results in array where index i + j + 1 holds current digit. Handle carry by adding to previous index. Solution Brief: Edge case: if either number is "0", return "0". Created result array of size n1 + n2 (max possible digits). Nested loops multiply each digit of num1 with each digit of num2. Accumulated results with proper carry handling. Built final string skipping leading zeros. #LeetCode #Day82 #100DaysOfCode #Math #String #Java #Algorithm #CodingChallenge #ProblemSolving #MultiplyStrings #MediumProblem #Multiplication #Array #DSA
To view or add a comment, sign in
-
-
Day 51: Tackling the "Hard" 🧠 Problem 761: Special Binary String After a streak of "easy"s, the difficulty spiked. This one was essentially a parentheses-balancing problem disguised as binary. The Strategy: • Identify: Tracked "Special" substrings using a balance counter. • Recurse: Processed inner strings recursively to find their best forms. • Sort: Reverse-sorted the resulting components to maximize the value. Ngl, I needed a hand with the implementation, but the logic—treating binary strings like nested structures—finally clicked. Sometimes you have to get cooked to learn. 🧗♂️ #LeetCode #Java #Recursion #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
🚀 Day 20 of #100DaysOfCode Solved 54. Spiral Matrix on LeetCode 🌀 🧠 Key insight: Spiral traversal is all about maintaining boundaries. By shrinking the top, bottom, left, and right limits after each pass, we can cover every element exactly once. ⚙️ Approach: 🔹Maintain four pointers: top, down, left, right 🔹Traverse: 🔹Left → Right (top row) 🔹Top → Bottom (right column) 🔹Right → Left (bottom row) 🔹Bottom → Top (left column) 🔹Update boundaries after each traversal ⏱️ Time Complexity: O(m × n) 📦 Space Complexity: O(1) (excluding output list) #100DaysOfCode #LeetCode #DSA #Matrix #Java #ProblemSolving #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
-
Day 58/100 – LeetCode Challenge ✅ Problem: Longest Balanced Substring II Difficulty: Medium Language: Java Approach: Multiple Pattern Detection + Prefix Difference Mapping Time Complexity: O(n) Space Complexity: O(n) Key Insight: Balanced substrings must have equal counts of characters in three possible patterns: Single character run - consecutive same characters Two characters - equal occurrences of two specific chars Three characters - all three chars appear same number of times Solution Brief: countOne(): Track longest consecutive run of same character. countTwo(): For two chars (like 'a'/'b'), use prefix sum where n1=+1, n2=-1; reset on other chars. countThree(): Track differences (a-b) and (a-c) as state; when same state repeats, balanced substring found. #LeetCode #Day58 #100DaysOfCode #String #HashMap #Java #Algorithm #CodingChallenge #ProblemSolving #LongestBalancedSubstringII #HardProblem #PrefixSum #StateTracking #DSA
To view or add a comment, sign in
-
-
Day 62: Recursive Patterns 🌀 Problem 1545: Find Kth Bit in Nth Binary String Today was all about string evolution. The task: generate a sequence where each string is formed by taking the previous one, adding a "1", and then appending the reversed and inverted version of the previous string. I took the simulation route for this one. I used a StringBuilder to progressively build the sequence up to N. In each step, I captured the previous state, reversed it, flipped the bits, and glued it all together. It’s a literal implementation of the problem's rules that makes the growth of the string easy to visualize. The brute force simulation worked, but with the string length doubling every iteration (2ⁿ − 1), it definitely tests the limits of heap memory for larger N. It’s a great reminder that while building the whole string is satisfying, there’s usually a hidden recursive logic that can find the answer without storing the entire sequence. We keep moving! 🚀 #LeetCode #Java #StringManipulation #CodingChallenge #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
Day 81/100 – LeetCode Challenge ✅ Problem: #11 Container With Most Water Difficulty: Medium Language: Java Approach: Two Pointers (Greedy Shrinking) Time Complexity: O(n) Space Complexity: O(1) Key Insight: Area = min(height[i], height[j]) × (j - i) Start with widest container (i=0, j=n-1). Move the pointer with smaller height inward — only this can potentially increase area. Solution Brief: Initialized two pointers at both ends. While i < j: Compute current area using smaller height Update max if current area larger Move the pointer with smaller height inward #LeetCode #Day81 #100DaysOfCode #TwoPointers #Java #Algorithm #CodingChallenge #ProblemSolving #ContainerWithMostWater #MediumProblem #Greedy #Array #DSA
To view or add a comment, sign in
-
-
🎯 Day 100 of #100DaysOfCode 🔥 What a way to wrap it up! Solved LeetCode #3666 – Minimum Operations to Equalize Binary String ✅ A problem that blends math, parity logic, and careful case analysis—not your usual binary flip question. Key takeaways: -> Count-based optimization over brute force -> Handling even/odd operation patterns smartly -> Early exits = cleaner & faster logic -> Thinking in terms of operations feasibility rather than simulation 🧠 Language: Java -> Runtime: 0 ms (Beats 83.87%) -> Memory: 47.90 MB 100 days. Countless problems. One habit built: consistency 💪 Onward to harder problems and deeper concepts 🚀 #LeetCode #Java #DSA #BinaryStrings #ProblemSolving #Consistency #100DaysChallenge
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