1573. Number of Ways to Split a String
SourceBiweekly Contest 34 Q2DifficultyMediumRating1590
Description
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'.
Solutions
Solution 1: Counting
Thinking
Split the string into three pieces with equally many ones. \(n\le 10^5\), so we cannot try every pair of cuts. Each piece must contain exactly one third of the ones.
If the total is not divisible by three there is no split; if there is no one at all, any two cuts work and the count is \(C_{n-1}^{2}\). Otherwise the first cut may sit anywhere between the \(\textit{cnt}\)-th and \((\textit{cnt}+1)\)-th one, and the second cut between the \(2\textit{cnt}\)-th and \((2\textit{cnt}+1)\)-th. The product of those two gap lengths is the answer.
First, we traverse the string \(s\) and count the number of characters \(1\), denoted as \(\textit{cnt}\). If \(\textit{cnt}\) cannot be divided by \(3\), then it is impossible to split the string, so we directly return \(0\). If \(\textit{cnt}\) is \(0\), it means there are no characters \(1\) in the string. We can choose any two positions out of \(n-1\) positions to split the string into three substrings, so the number of ways is \(C_{n-1}^2\).
If \(\textit{cnt} \gt 0\), we update \(\textit{cnt}\) to \(\frac{\textit{cnt}}{3}\), which is the number of characters \(1\) in each substring.
Next, we find the minimum index of the right boundary of the first substring, denoted as \(i_1\), and the maximum index of the right boundary of the first substring (exclusive), denoted as \(i_2\). Similarly, we find the minimum index of the right boundary of the second substring, denoted as \(j_1\), and the maximum index of the right boundary of the second substring (exclusive), denoted as \(j_2\). Then the number of ways is \((i_2 - i_1) \times (j_2 - j_1)\).
Note that the answer may be very large, so we need to take the modulo \(10^9+7\).
The time complexity is \(O(n)\), and the space complexity is \(O(1)\), where \(n\) is the length of the string \(s\).
Similar problems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |