Number of Good Ways to Split a String Problem
Description
LeetCode Problem 1525.
You are given a string s.
A split is called good if you can split s into two non-empty strings s_left and s_right where their concatenation is equal to s (i.e., s_left + s_right = s) and the number of distinct letters in s_left and s_right is the same.
Return the number of good splits you can make in s.
Example 1:
Input: s = "aacaba"
Output: 2
Explanation: There are 5 ways to split "aacaba" and 2 of them are good.
("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.
("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.
("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).
("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.
Example 2:
Input: s = "abcd"
Output: 1
Explanation: Split the string as follows ("ab", "cd").
Constraints:
1 <= s.length <= 10^5sconsists of only lowercase English letters.
Solution
Approach: Distinct Counts on Both Sides in One Pass
Counting the distinct letters of both parts from scratch at every cut would be O(n2). Instead, move the cut from left to right and update both sides one character at a time.
- Before the scan, the right part is the whole string: count how many times each letter occurs in it, and how many distinct letters it has.
- When the cut moves past character
c,cjoins the left part: if it is a letter we have not seen on the left yet, the left part gets one more distinct letter. It also leaves the right part: decrease its count, and if that count drops to0, the right part loses a distinct letter. - If the two distinct counts are equal, this cut is a good split.
Only the cuts after positions 0 to n - 2 are tried, so both parts are always non-empty. The letters are lowercase, so arrays of size 26 are enough.
Complexity: O(n) time and O(1) extra space (the two arrays have 26 entries).
class Solution:
def numSplits(self, s: str) -> int:
right = [0] * 26 # letter counts of the right part
for c in s:
right[ord(c) - 97] += 1
right_distinct = sum(1 for x in right if x > 0)
seen = [False] * 26 # letters in the left part
left_distinct = ans = 0
for c in s[:-1]: # both parts must be non-empty
k = ord(c) - 97
if not seen[k]:
seen[k] = True
left_distinct += 1
right[k] -= 1
if right[k] == 0:
right_distinct -= 1
if left_distinct == right_distinct:
ans += 1
return ans