Skip to content

1573. Number of Ways to Split a String

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 <= 105
  • s[i] is either '0' or '1'.

 

Solutions

Solution: Math

  • Time complexity: O(n)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {string} s
 * @return {number}
 */
const numWays = function (s) {
  const MODULO = 10 ** 9 + 7;
  const size = s.length;
  let count = 0;

  for (const char of s) {
    char === '1' && (count += 1);
  }
  if (count % 3) return 0;
  if (count === 0) return (((size - 1) * (size - 2)) / 2) % MODULO;
  let current = (first = second = 0);

  count /= 3;

  for (const char of s) {
    if (char === '1') current += 1;
    if (current === count) first += 1;
    if (current === count * 2) second += 1;
  }
  return (first * second) % MODULO;
};

Released under the MIT license