Maximum Number of Non-Overlapping Substrings Problem
Description
LeetCode Problem 1520.
Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:
- The substrings do not overlap, that is for any two substrings
s[i..j]ands[x..y], eitherj < xori > yis true. - A substring that contains a certain character
cmust also contain all occurrences ofc.
Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.
Notice that you can return the substrings in any order.
Example 1:
Input: s = "adefaddaccc"
Output: ["e","f","ccc"]
Explanation: The following are all the possible substrings that meet the conditions:
[
"adefaddaccc"
"adefadda",
"ef",
"e",
"f",
"ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
Example 2:
Input: s = "abbaccd"
Output: ["d","bb","cc"]
Explanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
Constraints:
1 <= s.length <= 10^5scontains only lowercase English letters.
Solution
Approach: Minimal Valid Segments, then Greedy by Right End
Record the first and last position of every letter. A valid substring that contains a letter must span at least from that letter's first to its last occurrence, and then also cover every other letter inside that range, and so on.
Step 1: candidate segments. It is enough to consider, for each letter c, the smallest valid substring that starts at first[c]. Start with [l, r] = [first[c], last[c]] and scan from l to r:
- If a letter in the range has its first occurrence before
l, no valid substring can start atl, so discard this candidate. - Otherwise extend
rto that letter's last occurrence and keep scanning (the range may grow while we scan it).
This gives at most 26 segments. Any valid substring contains one of them, so choosing among these segments loses nothing, and they are the shortest choices.
Step 2: pick them. Two valid segments are either disjoint or one contains the other; they cannot partly overlap, because the overlapping letters would force each one to contain the other. Sort the segments by right end and take every segment whose left end is after the last chosen right end. This is the classic interval-scheduling greedy, so it gives the maximum count. When one segment is nested inside another, the inner one ends first and is taken first, so the total length is also as small as possible.
Complexity: O(26 · n) time, since each of the at most 26 scans is O(n), and O(1) extra space besides the answer.
class Solution:
def maxNumOfSubstrings(self, s: str) -> List[str]:
first, last = {}, {}
for i, c in enumerate(s):
first.setdefault(c, i)
last[c] = i
# For each letter, the smallest valid substring that starts at its first occurrence.
segments = []
for l in first.values():
r, i = last[s[l]], l
while i <= r:
if first[s[i]] < l:
break # this letter also appears before l: no valid substring starts at l
r = max(r, last[s[i]])
i += 1
if i > r:
segments.append((l, r))
# Valid segments never partly overlap, so take them greedily by right end.
segments.sort(key=lambda seg: seg[1])
ans, end = [], -1
for l, r in segments:
if l > end:
ans.append(s[l : r + 1])
end = r
return ans