#3714
Longest Balanced Substring II
MediumHash TableStringPrefix SumHash 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 a sliding window to find the longest balanced substring efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Use a hashmap to maintain character counts as you expand the window.
- 2Step 2: Check if all characters in the hashmap have the same frequency.
- 3Step 3: Adjust the window size based on character counts to maintain balance.
solution.py13 lines
1def longest_balanced_substring(s):
2 max_length = 0
3 for length in range(1, len(s) + 1):
4 freq = {}
5 for i in range(len(s)):
6 if i >= length:
7 freq[s[i - length]] -= 1
8 if freq[s[i - length]] == 0:
9 del freq[s[i - length]]
10 freq[s[i]] = freq.get(s[i], 0) + 1
11 if len(freq) > 0 and len(set(freq.values())) == 1:
12 max_length = max(max_length, length)
13 return max_lengthℹ
Complexity note: The algorithm efficiently checks character frequencies in linear time, using a hashmap for storage.
- 1Balanced substrings require equal character frequency.
- 2Sliding window helps manage character counts efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.