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 109 + 7.
Example 1:
Input: s = "10101" Output: 4 Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'. "1|010|1" "1|01|01" "10|10|1" "10|1|01"
Example 2:
Input: s = "1001" Output: 0
Example 3:
Input: s = "0000" Output: 3 Explanation: There are three ways to split s in 3 parts. "0|0|00" "0|00|0" "00|0|0"
Constraints:
3 <= s.length <= 105s[i] is either '0' or '1'.This approach primarily involves the calculation of the number of '1's in the string and then leveraging prefix sums to determine viable partition points:
totalOnes.onesPerPart = totalOnes / 3.firstPartEnds and secondPartStarts.onesPerPart '1's have been seen.The Python solution reads the entire string to count the '1's initially. Using modular arithmetic, if the ones count is zero, it calculates combinations of splitting zeroes correctly. For non-zero ones, it identifies break points based on index locations for effectively segmenting the string post-sufficient counts of '1's.
JavaScript
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) given that extra space used doesn't scale with input size.
This approach uses a combinatorial logic to find the possible splits:
The C++ implementation uses standard library functions to simplify the counting process and leverages modulus arithmetic to handle large output, ensuring integer overflow does not occur.
Time Complexity: O(n), as we process the string linearly.
Space Complexity: O(1), as we only require a fixed count of variables proportionate to input size.
| Approach | Complexity |
|---|---|
| Prefix Sum Counting | Time Complexity: O(n) where n is the length of the string. |
| Mathematical Combination | Time Complexity: O(n), as we process the string linearly. |
Split a String Into the Max Number of Unique Substrings - Leetcode 1593 - Python • NeetCodeIO • 12,112 views views
Watch 9 more video solutions →Practice Number of Ways to Split a String with our built-in code editor and test cases.
Practice on FleetCode