Taro Logo

Longest Balanced Substring After One Swap

#6 Most AskedMedium
0 views
Topics:
StringsTwo PointersSliding Windows

You are given a binary string s consisting only of characters '0' and '1'.

A string is balanced if it contains an equal number of '0's and '1's.

You can perform at most one swap between any two characters in s. Then, you select a balanced substring from s.

Return an integer representing the maximum length of the balanced substring you can select.

Example 1:

Input: s = "100001"

Output: 4

Explanation:

  • Swap "100001". The string becomes "101000".
  • Select the substring "101000", which is balanced because it has two '0's and two '1's.

Example 2:

Input: s = "111"

Output: 0

Explanation:

  • Choose not to perform any swaps.
  • Select the empty substring, which is balanced because it has zero '0's and zero '1's.

Constraints:

  • 1 <= s.length <= 105
  • s consists only of the characters '0' and '1'.

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 should we return if the string is empty or has a length of less than 2, given that no swap can form a balanced substring?
  2. Does the 'at most one swap' mean we are restricted to swapping two characters *within* the target substring itself, or can we swap any two characters anywhere in the entire string?
  3. If multiple disjoint substrings can achieve the maximum length after a swap, should we return just the length of the longest one?
  4. Are we guaranteed that the input string will contain an equal number of '(' and ')' characters, or can there be an imbalance?
  5. When we perform a swap, does the swap operation permanently modify the original string for subsequent checks, or are we evaluating hypothetical single swaps for each potential substring?

Brute Force Solution

Approach

The problem asks for the maximum length of a balanced substring achievable after at most one swap of characters. A substring can be balanced without any swap if it already has equal counts of zeros and ones. Alternatively, a substring with an imbalance of two can be balanced by swapping one excess character with a needed character from outside the substring.

Here's how the algorithm would work step-by-step:

  1. Count the total number of zeros and ones available in the entire string.
  2. Maintain a running balance by adding one for character '1' and subtracting one for character '0'.
  3. Record the first index where each balance value is encountered using a hash map.
  4. Check if the identical balance appeared previously to update the longest naturally balanced substring.
  5. Check if a balance differing by two or negative two appeared previously, and verify if an outside character of the required type is available to perform the swap.
  6. Return the maximum balanced substring length found.

Code Implementation

def longest_balanced_substring(s: str) -> int:
    total_zeros = s.count('0')
    total_ones = len(s) - total_zeros
    
    # Track the earliest index where each balance difference was observed
    earliest_seen = {}
    earliest_seen[0] = -1
    current_balance = 0
    max_length = 0
    
    # Process the binary string and evaluate potential balanced windows
    for current_index, character in enumerate(s):
        current_balance += 1 if character == '1' else -1
        
        if current_balance in earliest_seen:
            window_length = current_index - earliest_seen[current_balance]
            if window_length > max_length:
                max_length = window_length
        else:
            earliest_seen[current_balance] = current_index
        
        # Check if swapping a character from outside can balance a difference of 2
        for balance_diff in (-2, 2):
            target_balance = current_balance - balance_diff
            if target_balance in earliest_seen:
                window_length = current_index - earliest_seen[target_balance]
                window_ones = (window_length + balance_diff) // 2
                window_zeros = window_length - window_ones
                
                if balance_diff == 2 and total_zeros > window_zeros:
                    if window_length > max_length:
                        max_length = window_length
                elif balance_diff == -2 and total_ones > window_ones:
                    if window_length > max_length:
                        max_length = window_length
                        
    return max_length

Big(O) Analysis

Time Complexity
O(n) – We iterate through the string of length n once, performing constant-time hash map lookups and arithmetic operations at each step.
Space Complexity
O(n) – The hash map stores at most 2n + 1 distinct balance values encountered along the string prefix.

Optimal Solution

Approach

Treat each one as plus one and each zero as minus one. A stretch is already balanced when the running total returns to a value seen before. One swap can also repair a stretch that is off by exactly two, if the character you need still exists outside that stretch. Remembering where each running total first appeared finds the longest stretch in one pass.

Here's how the algorithm would work step-by-step:

  1. Count the zeros and the ones in the whole string.
  2. Walk from left to right, adding one for a one and subtracting one for a zero.
  3. Remember every index where each running total appears.
  4. If this running total appeared earlier, the stretch between those points is already balanced. Keep the longest one.
  5. If a running total two lower appeared, the stretch has two extra ones. It becomes balanced by swapping in an outside zero, which is possible when the stretch does not already hold every zero. Try the earliest start, then the next start if the earliest one swallows every zero.
  6. Do the same for a running total two higher, which means two extra zeros and needs an outside one.
  7. The longest stretch found is the answer. A string of only one character has no balanced substring, so the answer is zero.

Code Implementation

def longest_balanced(s):
    zero_count = s.count("0")
    one_count = len(s) - zero_count
    positions = {0: [-1]}
    best_length = 0
    balance = 0
    for index, character in enumerate(s):
        balance += 1 if character == "1" else -1
        positions.setdefault(balance, []).append(index)
        best_length = max(best_length, index - positions[balance][0])
        for offset, outside_count in ((-2, zero_count), (2, one_count)):
            earlier = positions.get(balance + offset)
            if earlier is None:
                continue
            length_from_first = index - earlier[0]
            minority_inside = (length_from_first - 2) // 2
            if minority_inside < outside_count:
                best_length = max(best_length, length_from_first)
            elif len(earlier) > 1:
                best_length = max(best_length, index - earlier[1])
    return best_length

Big(O) Analysis

Time Complexity
O(n) – Each character is visited once, and each running total looks up a constant amount of earlier positions.
Space Complexity
O(n) – The map stores an index for every character, plus the starting sentinel.

Edge Cases

Empty string or string with a single parenthesis
How to Handle:
Return zero immediately since a valid balanced substring requires at least two characters.
String already completely balanced without any swaps
How to Handle:
The algorithm must correctly compute the full length of the string and allow a zero-effect swap if necessary.
String containing an odd number of parentheses
How to Handle:
Ensure the logic naturally caps the maximum possible balanced substring length to an even number.
String with an unequal count of opening and closing parentheses
How to Handle:
Pre-counting total parentheses allows the algorithm to determine if a global fix via a single swap is even mathematically possible.
Extremely long strings reaching maximum constraint limits
How to Handle:
An optimized linear or sub-quadratic approach must be used to avoid time limit exceeded errors in FAANG interviews.
Strings consisting entirely of opening or entirely of closing brackets
How to Handle:
The solution must gracefully handle the scenario where no valid balanced substring greater than two can be formed.
Swapping characters outside the target substring to fix it
How to Handle:
Ensure the swap logic strictly applies within or directly contributes to the contiguous window being evaluated.
0/29 completed