Taro Logo

Longest Balanced Substring II

Medium
Asked by:
Tata Consultancy Services
1 view
Topics:
Strings

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 <= 105
  • s contains only the characters 'a', 'b', and 'c'.

Solution


Clarifying Questions

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:

  1. What are the constraints on the length of the input string?
  2. How should we handle an empty string or a string with no balanced substrings (should we return 0)?
  3. Could you clarify the definition of 'distinct characters present in the substring'? Does it mean *all* characters in the substring must have the same frequency, or just that the set of characters present all share an equal count?
  4. Are uppercase English letters possible, or is the input strictly restricted to lowercase English letters?
  5. If multiple balanced substrings share the maximum length, does it matter which one's length we return, since we only need the maximum length?

Brute Force Solution

Approach

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:

  1. Find the maximum length of contiguous substrings consisting of a single repeating character.
  2. For each pair of allowed characters, reset state tracking whenever the third excluded character appears.
  3. Track the running difference between the counts of the two allowed characters using a hash map to find the longest equal-count segments.
  4. Track the running differences of all three characters simultaneously using a pair of relative differences stored in a hash map.
  5. Return the maximum balanced length discovered across all cases.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(N) – We iterate over the string of length N a constant number of times (once for single characters, three times for pairs of characters, and once for all three characters), performing constant-time hash map operations at each index.
Space Complexity
O(N) – The hash maps store prefix index states, which in the worst case can contain up to O(N) unique prefix difference entries.

Optimal Solution

Approach

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:

  1. Initialize the overall maximum length to one and prepare prefix frequency difference tracking for substrings with all three characters.
  2. Iterate over the string to compute difference signatures between character counts and find maximum lengths where all three characters occur equally.
  3. For each pair of characters, scan the string segments that avoid the third character to find maximum balanced subsegments of two distinct characters.
  4. Scan consecutive identical characters to account for balanced substrings composed of only one distinct character.
  5. Return the maximum length found among all evaluated single-character, two-character, and three-character balanced substrings.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(N) – We iterate over the string of length N a constant number of times (once for three characters, three times for pairs of characters, and once for single runs), performing O(1) hash map operations at each step.
Space Complexity
O(N) – The hash maps storing difference tuples and earlier indices require O(N) space in the worst case where every prefix generates a distinct difference state.

Edge Cases

Empty string or null input
How to Handle:
Return zero immediately as no balanced substring can exist in an empty or non-existent sequence.
String of length one
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Reset frequency tracking and state maps independently for each distinct character count iteration to avoid cross-contamination.