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
Number of Ways to Split a String INPUT Binary String s = "10101" 1 idx 0 0 idx 1 1 idx 2 0 idx 3 1 idx 4 Total Ones Count ones = 3 Split into 3 parts with equal ones (1 each) Input: s = "10101" ALGORITHM STEPS 1 Count Total Ones ones = 3, need 1 per part 2 Check Divisibility 3 % 3 == 0 (valid!) 3 Find Split Points After 1st & 2nd ones 4 Count Zero Gaps ways = (g1+1) * (g2+1) Split Positions 1 0 1 0 1 gap1 gap2 Formula: (1+1) * (1+1) = 2 * 2 = 4 FINAL RESULT All 4 Valid Splits: 1: "1" | "01" | "01" ones: 1, 1, 1 - OK 2: "1" | "010" | "1" ones: 1, 1, 1 - OK 3: "10" | "1" | "01" ones: 1, 1, 1 - OK 4: "10" | "10" | "1" ones: 1, 1, 1 - OK OUTPUT 4 4 ways to split with equal ones in each part Key Insight: If total ones are divisible by 3, count zeros between the 1st and 2nd third of ones (gap1), and between 2nd and 3rd third (gap2). Answer = (gap1 + 1) * (gap2 + 1) mod (10^9 + 7). Time: O(n), Space: O(1). If ones = 0, answer = C(n-1, 2) = (n-1)*(n-2)/2. TutorialsPoint - Number of Ways to Split a String | Mathematical Approach
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