Minimum Substring Partition of Equal Character Frequency Problem
Description
LeetCode Problem 3144.
Given a string s, you need to partition it into one or more balanced substrings. For example, if s == "ababcc" then ("abab", "c", "c"), ("ab", "abc", "c"), and ("ababcc") are all valid partitions, but ("a", **"bab"**, "cc"), (**"aba"**, "bc", "c"), and ("ab", **"abcc"**) are not. The unbalanced substrings are bolded.
Return the minimum number of substrings that you can partition s into.
Note: A balanced string is a string where each character in the string occurs the same number of times.
Example 1:
Input: s = "fabccddg"
Output: 3
Explanation:
We can partition the string s into 3 substrings in one of the following ways: ("fab, "ccdd", "g"), or ("fabc", "cd", "dg").
Example 2:
Input: s = "abababaccddb"
Output: 2
Explanation:
We can partition the string s into 2 substrings like so: ("abab", "abaccddb").
Constraints:
1 <= s.length <= 1000sconsists only of English lowercase letters.
Solution
Approach: Memoized Search + Hash Table
Let dfs(i) be the minimum number of balanced substrings needed for s[i:]; the answer is dfs(0), and dfs(i) = 0 when i >= n.
For dfs(i), extend the substring one character at a time, keeping cnt (occurrences of each letter) and freq (how many letters have each occurrence count). The substring s[i..j] is balanced when freq has exactly one key, and then 1 + dfs(j + 1) is a candidate. Take the minimum over all j, and cache the result per i.
Complexity: time O(n^2), space O(n * 26).
from collections import defaultdict
from functools import lru_cache
class Solution:
def minimumSubstringsInPartition(self, s: str) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
if i >= n:
return 0
cnt = defaultdict(int)
freq = defaultdict(int)
ans = n - i
for j in range(i, n):
if cnt[s[j]]:
freq[cnt[s[j]]] -= 1
if not freq[cnt[s[j]]]:
freq.pop(cnt[s[j]])
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
if len(freq) == 1 and (t := 1 + dfs(j + 1)) < ans:
ans = t
return ans
n = len(s)
return dfs(0)