#2609

Find the Longest Balanced Substring of a Binary String

Easy
StringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a HashMap to track the balance of zeroes and ones as we iterate through the string. This allows us to find the longest balanced substring in linear time by leveraging the concept of prefix sums.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize a HashMap to store the first occurrence of each balance value.
  2. 2Step 2: Initialize variables for balance (0) and max_length (0).
  3. 3Step 3: Iterate through the string, updating the balance: +1 for '1' and -1 for '0'.
  4. 4Step 4: If the balance is seen before, calculate the length of the substring from the first occurrence to the current index.
  5. 5Step 5: If the balance is new, store the current index in the HashMap.
  6. 6Step 6: Return the max_length found.
solution.py11 lines
1def longestBalancedSubstring(s):
2    balance_map = {0: -1}
3    balance = 0
4    max_length = 0
5    for i, char in enumerate(s):
6        balance += 1 if char == '1' else -1
7        if balance in balance_map:
8            max_length = max(max_length, i - balance_map[balance])
9        else:
10            balance_map[balance] = i
11    return max_length

Complexity note: This complexity is linear because we traverse the string once and use a HashMap to store balance indices, which allows for quick lookups.

  • 1Balanced substrings require equal counts of '0's and '1's.
  • 2Using a HashMap can optimize the search for previously seen balances.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.