LeetCode 3714: Longest Balanced Substring II

🚀 Day 503 of #750DaysOfCode 🔥 LeetCode 3714 — Longest Balanced Substring II (Medium) Today’s challenge was all about prefix differences, hashing, and smart optimization. We’re given a string containing only 'a', 'b', and 'c'. A substring is called balanced if all distinct characters in that substring appear the same number of times. 🧠 Key Insight Since we only have 3 characters, instead of brute-forcing every substring (which would be O(n²) ❌), we can: Track prefix counts of a, b, c Store frequency differences Use a HashMap to detect when the same difference pair appears again If two prefixes have the same difference values: (countA - countB) (countB - countC) Then the substring between them is balanced ✅ 💡 Optimization Strategy This solution smartly breaks the problem into 3 cases: 1️⃣ Only one distinct character 2️⃣ Exactly two distinct characters 3️⃣ All three characters Each case is handled efficiently using prefix differences and HashMaps. Time Complexity: O(n) Space Complexity: O(n) No brute force. No nested loops. Just pure prefix logic. 🔥 What I Learned Today ✔ Prefix difference technique is powerful ✔ Hashing states helps avoid O(n²) brute force ✔ Breaking complex problems into structured cases simplifies thinking ✔ Medium problems often test observation, not complexity “The difference between good and great coders is not syntax — it’s pattern recognition.” Onward to Day 504 💪🔥 #LeetCode #DataStructures #Algorithms #Java #CodingJourney #750DaysOfCode #ProblemSolving #TechGrowth

  • text

To view or add a comment, sign in

Explore content categories