Number of Ways to Split a String - Problem

Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.

Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Equal Distribution
$ Input: s = "10101"
Output: 4
💡 Note: There are 4 ways to split: "1|010|1", "1|01|01", "10|10|1", "101|0|1". Each gives 1 one per part.
Example 2 — All Zeros
$ Input: s = "0000"
Output: 3
💡 Note: Any split gives 0 ones in each part. Possible splits: "0|0|00", "0|00|0", "00|0|0".
Example 3 — Impossible Split
$ Input: s = "101"
Output: 0
💡 Note: 2 ones cannot be split equally among 3 parts (2 ÷ 3 ≠ integer).

Constraints

  • 3 ≤ s.length ≤ 105
  • s consists only of '0' and '1' characters

Visualization

Tap to expand
Split Binary String: "10101" into 3 Equal Parts10101Input: Binary string with 3 onesPart 1Must containexactly 1 onePart 2Must containexactly 1 onePart 3Must containexactly 1 oneGoal: Count all valid ways to place 2 cut positionsValid splits: "1|010|1", "1|01|01", "10|10|1", "101|0|1"Result: 4 ways
Understanding the Visualization
1
Input Analysis
Binary string with ones and zeros
2
Split Requirement
3 non-empty parts with equal number of ones
3
Count Ways
Return number of valid split combinations
Key Takeaway
🎯 Key Insight: Use math to find valid cut ranges instead of trying all combinations
Asked in
Google 25 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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