Longest Balanced Substring II Problem
#3714
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3714.
You are given a string s consisting only of the characters 'a', 'b', and 'c'.
A substring of s is called balanced if all distinct characters in the substring appear the same number of times.
Return the length of the longest balanced substring of s.
Example 1:
Input: s = "abbac"
Output: 4
Explanation:
The longest balanced substring is "abba" because both distinct characters 'a' and 'b' each appear exactly 2 times.
Example 2:
Input: s = "aabcc"
Output: 3
Explanation:
The longest balanced substring is "abc" because all distinct characters 'a', 'b' and 'c' each appear exactly 1 time.
Example 3:
Input: s = "aba"
Output: 2
Explanation:
One of the longest balanced substrings is "ab" because both distinct characters 'a' and 'b' each appear exactly 1 time. Another longest balanced substring is "ba".
Constraints:
1 <= s.length <= 10^5scontains only the characters'a','b', and'c'.
Solution
Approach: Prefix Differences + Hash Table
A balanced substring has one, two or three distinct letters, so take the best of three cases.
- One letter, such as
"aaa": the longest run of equal characters. - Two letters
aandb, such as"aabb": work inside each stretch that contains onlyaandb. Keepd = (#a) - (#b)for the prefix and a hash table mapping eachdto its first position. Whendrepeats, the substring between the two positions has equal counts, so update the answer. Try all three letter pairs. - Three letters: the same idea with the key
(#a - #b, #b - #c); a repeated key means equal counts of all three letters.
The answer is the maximum over the cases.
Complexity: O(n) time and O(n) space.
from collections import Counter
class Solution:
def longestBalanced(self, s: str) -> int:
def calc1(s: str) -> int:
res = 0
i, n = 0, len(s)
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
res = max(res, j - i)
i = j
return res
def calc2(s: str, a: str, b: str) -> int:
res = 0
i, n = 0, len(s)
while i < n:
while i < n and s[i] not in (a, b):
i += 1
pos = {0: i - 1}
d = 0
while i < n and s[i] in (a, b):
d += 1 if s[i] == a else -1
if d in pos:
res = max(res, i - pos[d])
else:
pos[d] = i
i += 1
return res
def calc3(s: str) -> int:
pos = {(0, 0): -1}
cnt = Counter()
res = 0
for i, c in enumerate(s):
cnt[c] += 1
k = (cnt["a"] - cnt["b"], cnt["b"] - cnt["c"])
if k in pos:
res = max(res, i - pos[k])
else:
pos[k] = i
return res
x = calc1(s)
y = max(calc2(s, "a", "b"), calc2(s, "b", "c"), calc2(s, "a", "c"))
z = calc3(s)
return max(x, y, z)