Find the Longest Balanced Substring of a Binary String - Problem

You are given a binary string s consisting only of zeroes and ones.

A substring of s is considered balanced if:

  • All zeroes are before ones
  • The number of zeroes is equal to the number of ones

Notice that the empty substring is considered a balanced substring.

Return the length of the longest balanced substring of s.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Pattern
$ Input: s = "01000111"
Output: 6
💡 Note: The longest balanced substring is "000111" with 3 zeros followed by 3 ones, giving length 6
Example 2 — Multiple Patterns
$ Input: s = "00111"
Output: 4
💡 Note: We have 2 zeros and 3 ones in pattern. The longest balanced part is "0011" with length 4
Example 3 — No Valid Pattern
$ Input: s = "111"
Output: 0
💡 Note: No zeros present, so no balanced substring is possible

Constraints

  • 1 ≤ s.length ≤ 50
  • s consists only of '0' and '1'

Visualization

Tap to expand
Longest Balanced Substring INPUT Binary String s: 0 i=0 1 i=1 0 i=2 0 i=3 0 i=4 1 i=5 1 i=6 1 i=7 "000111" (Balanced) Legend: = Zero (0) = One (1) Balanced Substring: 1. All 0s come before all 1s 2. Count(0) == Count(1) Example: "0011", "000111" s = "01000111" ALGORITHM STEPS (Single Pass Optimization) 1 Initialize Counters zeros=0, ones=0, maxLen=0 2 Scan Left to Right Count consecutive 0s, then 1s 3 Update Max Length maxLen = 2 * min(zeros, ones) 4 Reset on New Zero When 0 follows 1, reset counters Execution Trace: Pos Char 0s 1s maxLen 0-1 01 1 1 2 2-4 000 3 0 2 5-7 111 3 3 6 min(3,3)*2 = 6 FINAL RESULT Longest Balanced Substring Found: "000111" Position: index 2 to 7 0 0 0 1 1 1 3 zeros = 3 ones Length = 3 + 3 = 6 Output: 6 OK Key Insight: Single Pass Optimization counts consecutive zeros followed by ones. When we see a '1' after '0s', we count ones. When pattern breaks (0 after 1), we update max length using min(zeros, ones) * 2 and reset. This achieves O(n) time complexity with O(1) space - no extra data structures needed! TutorialsPoint - Find the Longest Balanced Substring of a Binary String | Single Pass Optimization
Asked in
Amazon 25 Microsoft 18
8.5K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen