#1573
Number of Ways to Split a String
MediumMathString
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the fact that if the total number of '1's in the string is not divisible by 3, we can immediately return 0. Otherwise, we can count the occurrences of '1's and determine valid split points using prefix sums and combinations.
⚙️
Algorithm
4 steps- 1Step 1: Count the total number of '1's in the string. If it's not divisible by 3, return 0.
- 2Step 2: Calculate the target number of '1's per part (total_ones / 3).
- 3Step 3: Traverse the string and keep track of the number of '1's seen so far. Count how many times we reach the target number of '1's.
- 4Step 4: Use the counts of valid split points to calculate the number of ways to split the string.
solution.py19 lines
1# Full working Python code
2
3def countWays(s):
4 MOD = 10**9 + 7
5 total_ones = s.count('1')
6 if total_ones % 3 != 0:
7 return 0
8 target = total_ones // 3
9 count = 0
10 prefix_count = 0
11 ways = 0
12 for i in range(len(s)):
13 if s[i] == '1':
14 prefix_count += 1
15 if prefix_count == target:
16 count += 1
17 elif prefix_count == 2 * target:
18 ways += count
19 return ways % MODℹ
Complexity note: This complexity is linear because we only traverse the string a few times without using additional data structures that scale with input size.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.