Number of Ways to Split a String Problem
Description
LeetCode Problem 1573.
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^9 + 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 <= 10^5s[i]is either'0'or'1'.
Solution
Approach: Count the Gaps Around the Ones
Let total be the number of '1' characters. If it is not divisible by 3, no split works, so the answer is 0.
If there are no ones at all, every split is valid: we pick two of the n - 1 gaps between characters, which gives (n - 1)(n - 2) / 2 ways.
Otherwise each part needs exactly k = total / 3 ones. List the positions of the ones as ones[0], ones[1], ...:
- The first part must end after the
k-th one (ones[k-1]) and before the next one (ones[k]), so the first cut hasones[k] - ones[k-1]possible places. - Likewise the second cut must fall between
ones[2k-1]andones[2k], which givesones[2k] - ones[2k-1]places.
The two choices are independent, so the answer is the product of the two gap sizes, modulo 10^9 + 7. Both counts can reach about 10^5, and so can n, so compute the products in 64-bit integers before taking the modulo.
Complexity: O(n) time and O(n) extra space for the positions of the ones.
class Solution:
def numWays(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
ones = [i for i, c in enumerate(s) if c == '1']
if len(ones) % 3:
return 0
if not ones:
# all zeros: any two of the n - 1 gaps can be the cuts
return (n - 1) * (n - 2) // 2 % mod
k = len(ones) // 3 # ones per part
# the first cut goes anywhere between the k-th and (k+1)-th one, the second
# anywhere between the 2k-th and (2k+1)-th one
first = ones[k] - ones[k - 1]
second = ones[2 * k] - ones[2 * k - 1]
return first * second % mod