Find Maximum Number of Non Intersecting Substrings Problem
#3557
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3557.
You are given a string word.
Return the maximum number of non-intersecting substrings of word that are at least four characters long and start and end with the same letter.
Example 1:
Input: word = "abcdeafdef"
Output: 2
Explanation:
The two substrings are "abcdea" and "fdef".
Example 2:
Input: word = "bcdaaaab"
Output: 1
Explanation:
The only substring is "aaaa". Note that we cannot also choose "bcdaaaab" since it intersects with the other substring.
Constraints:
1 <= word.length <= 2 * 10^5wordconsists only of lowercase English letters.
Solution
Approach: Greedy Scan
A valid substring starts and ends with the same letter and has length at least 4, so its two equal letters are at least 3 positions apart. Finishing a substring as early as possible never hurts, because it leaves the most room for the next ones.
Scan left to right and remember, for each letter, its first occurrence since the last chosen substring. At index i with letter c:
- If
chas no remembered position, rememberi. - Otherwise, if
iis at least 3 past the remembered position, take that substring: count it and forget all remembered positions, so the next substring starts afteri. - Otherwise keep the earlier position (it can only help later).
Complexity: O(n) time and O(1) extra space (26 letters).
class Solution:
def maxSubstrings(self, word: str) -> int:
first = {} # letter -> earliest usable start since the last chosen substring
ans = 0
for i, c in enumerate(word):
if c not in first:
first[c] = i
elif i - first[c] >= 3:
ans += 1
first = {}
return ans