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 <= 105s contains only the characters 'a', 'b', and 'c'.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
A balanced substring can consist of one, two, or three distinct characters with equal frequencies. We can evaluate each of these three distinct cases separately to find the overall maximum length. Using hash maps to record prefix difference states allows each case to be solved in linear time.
Here's how the algorithm would work step-by-step:
def longest_balanced_substring(s: str) -> int:
max_length = 0
# Check single character runs
current_run = 0
previous_char = ''
for char in s:
if char == previous_char:
current_run += 1
else:
previous_char = char
current_run = 1
if current_run > max_length:
max_length = current_run
# Check substrings containing exactly two distinct characters
pairs = [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'c', 'a')]
for char1, char2, excluded_char in pairs:
diff_map = {0: -1}
diff = 0
segment_start = 0
for index, char in enumerate(s):
if char == excluded_char:
diff_map = {0: index}
diff = 0
segment_start = index + 1
else:
if char == char1:
diff += 1
elif char == char2:
diff -= 1
if diff in diff_map:
max_length = max(max_length, index - diff_map[diff])
else:
diff_map[diff] = index
# Check substrings containing all three characters
state_map = {(0, 0): -1}
count_a = 0
count_b = 0
count_c = 0
for index, char in enumerate(s):
if char == 'a':
count_a += 1
elif char == 'b':
count_b += 1
elif char == 'c':
count_c += 1
state = (count_a - count_b, count_b - count_c)
if state in state_map:
max_length = max(max_length, index - state_map[state])
else:
state_map[state] = index
return max_length
A balanced substring can consist of one, two, or three distinct characters having identical frequencies. We handle each scenario separately by tracking prefix difference states and recording their earliest occurrences. The maximum valid length across all possible character combinations yields the desired result.
Here's how the algorithm would work step-by-step:
def longest_balanced_substring(string_val: str) -> int:
# Initialize the maximum length observed to 1 since any single character is balanced
max_length = 1
char_counts = {'a': 0, 'b': 0, 'c': 0}
seen_diffs_three = {(0, 0): -1}
# First pass: check substrings containing all three characters with equal frequencies
for current_index, current_char in enumerate(string_val):
char_counts[current_char] += 1
diff_ba = char_counts['b'] - char_counts['a']
diff_ca = char_counts['c'] - char_counts['a']
diff_tuple = (diff_ba, diff_ca)
if diff_tuple in seen_diffs_three:
max_length = max(max_length, current_index - seen_diffs_three[diff_tuple])
else:
seen_diffs_three[diff_tuple] = current_index
# Second pass: check substrings containing only two distinct characters with equal frequencies
for char_x, char_y, excluded_char in [('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'c', 'a')]:
seen_diff_two = {0: -1}
diff_xy = 0
segment_start = 0
for current_index, current_char in enumerate(string_val):
if current_char == excluded_char:
seen_diff_two = {0: current_index}
diff_xy = 0
segment_start = current_index + 1
else:
diff_xy += 1 if current_char == char_x else -1
if diff_xy in seen_diff_two:
max_length = max(max_length, current_index - seen_diff_two[diff_xy])
else:
seen_diff_two[diff_xy] = current_index
# Third pass: check maximum run of consecutive identical characters
current_run = 1
for current_index in range(1, len(string_val)):
if string_val[current_index] == string_val[current_index - 1]:
current_run += 1
max_length = max(max_length, current_run)
else:
current_run = 1
return max_length
| Case | How to Handle |
|---|---|
| Empty string or null input | Return zero immediately as no balanced substring can exist in an empty or non-existent sequence. |
| String of length one | Return one because a single character substring trivially has all its distinct characters appearing the exact same number of times. |
| String with all identical characters | Return the full length of the string since there is only one distinct character and its frequency is uniform throughout. |
| Maximum length string within constraints | Ensure the algorithm uses an efficient linear or near-linear time approach to prevent time limit exceed errors. |
| Substrings with varying numbers of distinct characters | Iterate through all possible numbers of distinct characters from one to twenty-six to evaluate every valid frequency condition. |
| No balanced substring greater than length one | The algorithm correctly defaults to returning one by treating any single character as a valid trivial balanced substring. |
| Memory constraints with large alphabet size tracking | Use fixed-size frequency arrays or optimized hash maps to track character counts without excessive memory overhead. |
| Overlapping frequency states with different distinct character counts | Reset frequency tracking and state maps independently for each distinct character count iteration to avoid cross-contamination. |