Longest Substring with Equal Number of 0s and 1s

Problem Given a binary string consisting only of the characters '0' and '1', find the length of the longest contiguous substring that contains an equal number of 0s and 1s.

Input / Output

  • Input: a string s over the alphabet {'0','1'}.
  • Output: an integer — the length of the longest balanced substring, or 0 if no such substring exists.

Constraints

  • 1 <= |s| <= 10^5
  • Characters are limited to '0' and '1'.
  • Enumerating all substrings is O(n^2) and too slow at this size.

Example

  • s = "11010011" → 8; the whole string holds four 0s and four 1s.
  • s = "1100011" → 6; the prefix "110001" balances at three of each, while the full string does not.
  • s = "0000" → 0; no balanced substring exists.
asked …
LeaderboardSalaryAccount