Number of Ways to Split a String - Problem
Split Binary String Into Equal Parts

You're given a binary string s containing only '0's and '1's. Your task is to split this string into exactly 3 non-empty substrings such that each substring contains the same number of ones.

More formally, find the number of ways to split s into s1 + s2 + s3 where:
โ€ข Each substring is non-empty
โ€ข The count of '1's in s1 equals the count of '1's in s2 equals the count of '1's in s3

Example: For string "10101", we need each part to have exactly 1 one, so valid splits include: "1|01|01", "1|010|1", "10|1|01", "101|0|1"

Since the result can be very large, return it modulo 109 + 7.

Input & Output

example_1.py โ€” Basic case with equal distribution
$ Input: s = "10101"
โ€บ Output: 4
๐Ÿ’ก Note: We need each part to have 1 one. Valid splits: "1|01|01" (positions 1,3), "1|010|1" (positions 1,4), "10|1|01" (positions 2,3), "101|0|1" (positions 3,4). Total: 4 ways.
example_2.py โ€” All zeros edge case
$ Input: s = "1111"
โ€บ Output: 0
๐Ÿ’ก Note: We have 4 ones total. Since 4 is not divisible by 3, it's impossible to split into 3 parts with equal number of ones. Return 0.
example_3.py โ€” String with only zeros
$ Input: s = "0000"
โ€บ Output: 3
๐Ÿ’ก Note: All parts will have 0 ones regardless of how we split. We need to choose 2 cut positions from 3 possible positions (after positions 1, 2, or 3). This gives us C(3,2) = 3 ways: "0|0|00", "0|00|0", "00|0|0".

Constraints

  • 3 โ‰ค s.length โ‰ค 105
  • s[i] is either '0' or '1'
  • The string must be split into exactly 3 non-empty parts

Visualization

Tap to expand
Cookie Dough Roll with Chocolate ChipsFlexible Cut Zone 1(3 possible positions)Flexible Cut Zone 2(2 possible positions)Must have chip hereMust have chip hereMust have chip hereTotal ways = 3 ร— 2 = 6 different cutting combinationsEach person gets exactly the same number of chocolate chips!
Understanding the Visualization
1
Count the Chips
First count all chocolate chips (ones) in the dough roll
2
Check Divisibility
If chips can't be divided equally by 3, it's impossible
3
Find Required Boundaries
Identify where certain chips must be to ensure equal distribution
4
Count Flexible Zones
Between required chip positions, count the plain dough (zeros) where cuts can be made
5
Calculate Combinations
Multiply the flexibility in each cutting zone to get total possibilities
Key Takeaway
๐ŸŽฏ Key Insight: Once we know where the required chocolate chips (ones) must be positioned, we only need to count the flexible cutting zones (zeros) between them and multiply the possibilities!
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
52.3K Views
Medium Frequency
~18 min Avg. Time
1.8K 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