Number of Good Ways to Split a String - Problem
You are given a string s and need to find all the "good" ways to split it into two parts.
A split is considered good if:
- You can split
sinto two non-empty stringss_leftands_right - Their concatenation equals the original string:
s_left + s_right = s - The number of distinct characters in
s_leftequals the number of distinct characters ins_right
Goal: Return the total count of good splits possible.
Example: For string "aacaba", we can split it as "aa|caba" (2 distinct chars each) or "aac|aba" (2 distinct chars each), giving us 2 good splits.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aacaba"
โบ
Output:
2
๐ก Note:
Split at position 3: "aac|aba" gives 2 distinct chars each side. Split at position 4: "aaca|ba" gives 2 distinct chars each side. Total: 2 good splits.
example_2.py โ All Same Characters
$
Input:
s = "abcd"
โบ
Output:
1
๐ก Note:
Only one good split at position 2: "ab|cd" gives 2 distinct chars on each side. All other splits have unequal distinct character counts.
example_3.py โ Repeated Pattern
$
Input:
s = "aaaa"
โบ
Output:
3
๐ก Note:
All possible splits have 1 distinct character on both sides: "a|aaa", "aa|aa", "aaa|a". Total: 3 good splits.
Constraints
- 1 โค s.length โค 105
- s consists of only lowercase English letters
- Both parts must be non-empty after splitting
Visualization
Tap to expand
Understanding the Visualization
1
Count Left Genres
As we move the divider right, track distinct genres accumulated on the left
2
Calculate Right Genres
For each position, determine how many distinct genres remain on the right
3
Compare & Count
Count positions where left distinct genres equal right distinct genres
Key Takeaway
๐ฏ Key Insight: Pre-computing both prefix and suffix distinct character counts allows us to check each split in constant time, reducing complexity from O(nยฒ) to O(n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code