Number of Ways to Split a String - Problem
Split Binary String Into Equal Parts
You're given a binary string
More formally, find the number of ways to split
โข 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.
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code