Longest Balanced Substring in Java: Avoiding O(n²) Complexity

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

  • text

To view or add a comment, sign in

Explore content categories