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 s into two non-empty strings s_left and s_right
  • Their concatenation equals the original string: s_left + s_right = s
  • The number of distinct characters in s_left equals the number of distinct characters in s_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
Good String Splits VisualizationString: "aacaba" โ†’ Find splits where left and right have equal distinct charsa|acaba1 โ‰  3aa|caba1 โ‰  3aac|aba2 = 2 โœ“aaca|ba2 = 2 โœ“aacab|a3 โ‰  1Optimal Algorithm Steps:1. Forward PassCount distinct charsfor each prefix2. Backward PassCount distinct charsfor each suffix3. Compare ArraysCount positions whereprefix[i-1] = suffix[i]Array Values:Position:012345Prefix:112233Suffix:333221Good Splits Found:Split 1: prefix[2] = suffix[3] โ†’ 2 = 2 โœ“Split 2: prefix[3] = suffix[4] โ†’ 2 = 2 โœ“Total Good Splits: 2
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).
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 15
28.5K Views
Medium Frequency
~18 min Avg. Time
924 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen