VOOZH about

URL: https://www.geeksforgeeks.org/dsa/split-the-binary-string-into-substrings-with-equal-number-of-0s-and-1s/

⇱ Split a binary string into substrings with equal 0s and 1s - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Split a binary string into substrings with equal 0s and 1s

Last Updated : 10 May, 2026

Given binary string s . find the maximum number of substrings it can be splitted into such that all substrings have equal number of 0s and 1s. If it is not possible to split s satisfying the conditions then return -1.

Examples:

Input: s = "0100110101" 
Output:
Explanation: The required substrings are "01", "0011", "01" and "01".

Input: s = "0111100010" 
Output: 3
Explanation: The required substrings are "01", "111000" and "10"

Using Stack - O(n) Time O(n) Space

The idea is to use a stack to simulate cancellation of opposite characters (0 and 1), similar to balanced parentheses.

  • We push characters into the stack and whenever a different character is encountered, we pop from the stack.
  • Whenever the stack becomes empty, it indicates that a balanced substring is formed, so we increment the count.
  • After processing the entire string, if the stack is empty, we return the count; otherwise we return -1.

Output
4

Time Complexity: O(n)
Space Complexity: O(n)

Using Simple Traversal - O(n) Time O(1) Space

The idea is to traverse the string while counting 0s and 1s. Whenever both counts become equal, a balanced substring is found, so we increment the count. After traversal, if the total number of 0s and 1s are not equal, we return -1; otherwise, we return the count.


Output
4

Time Complexity: O(n)
Space Complexity: O(1)

Comment
Article Tags: