The Number of Good Ways to Split a String problem asks: for how many split positions can you divide a string into two non-empty parts such that both parts have the same number of distinct characters? This coding problem uses prefix and suffix distinct-character counts, efficiently maintained with a hash map or bit manipulation.
Meta, Amazon, and Google ask this because it tests efficient prefix/suffix tracking of distinct character counts. A brute-force O(n²) approach is too slow; the O(n) solution uses prefix sets and suffix sets updated incrementally. The hash table, string, bit manipulation, and dynamic programming interview pattern is applied.
Two-pass distinct count tracking. Pass 1 (left to right): compute leftDistinct[i] = number of distinct characters in s[0..i]. Pass 2 (right to left): compute rightDistinct[i] = number of distinct characters in s[i..n-1]. For each split point (between index i and i+1): count if leftDistinct[i] == rightDistinct[i+1].
Use bit manipulation: represent character sets as 26-bit integers. Adding a character = OR with bit for that character. Count = popcount.
s = "aacaba". Left distinct: a=1,a=1,c=2,a=2,b=3,a=3. Right distinct (from right): a=1,b=2,a=2,a=2,c=2,a=1... Recompute properly. Split at position 2 (left="aac", right="aba"): left distinct=2, right distinct=2 ✓. Count all valid splits.
Two-pass prefix/suffix array problems are extremely common. For any property P, precompute leftP[i] and rightP[i], then compare them at each split point. For distinct character count, a 26-bit integer bitmask is elegant: OR to add a character, popcount to get distinct count. Practice building prefix/suffix arrays for various properties (distinct chars, sum, max, min) — this is a reusable template for many string and array split problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Longest Ideal Subsequence | Medium | Solve | |
| Total Appeal of A String | Hard | Solve | |
| Find Longest Awesome Substring | Hard | Solve | |
| Palindrome Permutation | Easy | Solve | |
| Count Unique Characters of All Substrings of a Given String | Hard | Solve |