#3713
Longest Balanced Substring I
MediumHash TableStringCountingEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a hashmap to track character frequencies and check for balanced substrings efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Use a hashmap to count character frequencies as you iterate through the string.
- 2Step 2: For each unique frequency, check if all characters have that frequency.
- 3Step 3: Update the maximum length of balanced substrings found.
solution.py10 lines
1def longest_balanced(s):
2 max_len = 0
3 for freq in range(1, len(s) // 2 + 1):
4 count = {}
5 for char in s:
6 count[char] = count.get(char, 0) + 1
7 if count[char] == freq:
8 if len(set(count.values())) == 1:
9 max_len = max(max_len, sum(count.values()))
10 return max_lenℹ
Complexity note: Iterate through the string while maintaining counts, leading to linear time complexity.
- 1Balanced substrings require equal character frequencies.
- 2Using a hashmap allows efficient frequency counting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.