Maximum Number of Non-Overlapping Substrings - Problem
You're given a string s containing only lowercase letters. Your task is to find the maximum number of non-overlapping substrings that satisfy two crucial conditions:
- Non-overlapping: The substrings cannot share any characters (no overlap)
- Character completeness: If a substring contains a character
c, it must contain all occurrences ofcin the original string
Your goal is to maximize the number of such substrings. If multiple solutions exist with the same count, choose the one with minimum total length.
Example: For string "adefaddaccc", you could pick substrings like "adefadda" (contains all 'a's and 'd's) and "ccc" (contains all 'c's), giving you 2 non-overlapping valid substrings.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "adefaddaccc"
โบ
Output:
["adefadda", "ccc"]
๐ก Note:
The character 'a' appears at indices 0, 4, 7, so any substring containing 'a' must span at least from 0 to 7. Similarly, 'd' appears at 1, 5, 6, 'e' at 2, 'f' at 3, and 'c' at 8, 9, 10. The optimal solution picks "adefadda" (contains all a's, d's, e's, f's) and "ccc" (contains all c's), giving us 2 non-overlapping substrings.
example_2.py โ Single Character Groups
$
Input:
s = "abbaccd"
โบ
Output:
["abba", "cc", "d"]
๐ก Note:
Character 'a' appears at indices 0, 3, so we need positions 0-3 giving "abba". Character 'c' appears at 4, 5 giving "cc". Character 'd' appears only at 6 giving "d". This gives us 3 non-overlapping valid substrings, which is optimal.
example_3.py โ All Same Character
$
Input:
s = "aaaa"
โบ
Output:
["aaaa"]
๐ก Note:
Since all characters are the same ('a'), any valid substring must contain all occurrences of 'a'. Therefore, the entire string "aaaa" is the only possible valid substring, giving us 1 substring.
Constraints
- 1 โค s.length โค 105
- s contains only lowercase English letters
- The string is guaranteed to have at least one valid substring
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Street
Map where each family's houses (character occurrences) are located
2
Claim Territories
Starting from the left, claim the smallest territory that includes complete families
3
Maximize Count
Greedily select shortest territories to maximize the total number of territories
Key Takeaway
๐ฏ Key Insight: Use greedy approach - always claim the shortest territory that satisfies all family requirements, maximizing the total number of territories.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code