Select K Disjoint Special Substrings Problem
Description
LeetCode Problem 3458.
Given a string s of length n and an integer k, determine whether it is possible to select k disjoint special substrings.
A special substring is a substring where:
- Any character present inside the substring should not appear outside it in the string.
- The substring is not the entire string
s.
Note that all k substrings must be disjoint, meaning they cannot overlap.
Return true if it is possible to select k such disjoint special substrings; otherwise, return false.
Example 1:
Input: s = "abcdbaefab", k = 2
Output: true
Explanation:
- We can select two disjoint special substrings: "cd" and "ef".
- "cd" contains the characters 'c' and 'd', which do not appear elsewhere in s.
- "ef" contains the characters 'e' and 'f', which do not appear elsewhere in s.
Example 2:
Input: s = "cdefdc", k = 3
Output: false
Explanation:
There can be at most 2 disjoint special substrings: "e" and "f". Since k = 3, the output is false.
Example 3:
Input: s = "abeabe", k = 0
Output: true
Constraints:
2 <= n == s.length <= 5 * 10^40 <= k <= 26sconsists only of lowercase English letters.
Solution
Approach: Candidate Intervals + Greedy Selection
If a special substring contains a letter, it must contain every occurrence of it. So every special substring contains, for each of its letters c, the whole span from the first to the last occurrence of c. It follows that we only need the smallest special substring that starts at the first occurrence of each letter: if some bigger special substring is chosen, it contains such a smaller one, so it is never needed.
For each letter c present in s, start with l = first[c] and r = last[c]. Scan j from l while j <= r: if the letter at j first appears before l, this start is invalid; otherwise extend r to last of that letter. If the scan succeeds and the interval [l, r] is not the whole string, it is a candidate. There are at most 26 candidates.
Now we want the maximum number of disjoint intervals, the classic interval scheduling problem: sort by right end and take an interval whenever it starts after the last taken one ends. The answer is true when the count is at least k (so always true for k = 0).
Complexity: O(26 n) time and O(26) extra space.
class Solution:
def maxSubstringLength(self, s: str, k: int) -> bool:
n = len(s)
first, last = {}, {}
for i, c in enumerate(s):
first.setdefault(c, i)
last[c] = i
segs = []
for c in first:
l, r = first[c], last[c]
ok = True
j = l
while j <= r:
x = s[j]
if first[x] < l:
ok = False
break
r = max(r, last[x])
j += 1
if ok and not (l == 0 and r == n - 1):
segs.append((r, l))
segs.sort()
cnt, end = 0, -1
for r, l in segs:
if l > end:
cnt += 1
end = r
return cnt >= k