Maximum Number of Non-Overlapping Substrings - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aabcc"
›
Output:
["aa", "b", "cc"]
💡 Note:
Character 'a' appears at indices 0,1 so any substring with 'a' must include both. Similarly 'c' at indices 3,4. The substring "b" at index 2 is valid alone. All three substrings are non-overlapping.
Example 2 — Single Character
$
Input:
s = "aba"
›
Output:
["aba"]
💡 Note:
Character 'a' appears at indices 0,2 so any substring containing 'a' must span the entire string. The optimal solution is the whole string.
Example 3 — All Different
$
Input:
s = "abcd"
›
Output:
["a", "b", "c", "d"]
💡 Note:
Each character appears exactly once, so each character forms its own valid substring. Maximum count is 4.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String "aabcc" with character positions
2
Valid Substrings
Find substrings containing all occurrences of their characters
3
Non-Overlapping Selection
Choose maximum number without overlap
Key Takeaway
🎯 Key Insight: If a substring contains a character, it must contain ALL occurrences of that character to be valid
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code