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] and s[x..y], either j < x or i > y is true.
  • A substring that contains a certain character c must also contain all occurrences of c.

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
Maximum Non-Overlapping SubstringsInput: "aabcc"aabcc01234Valid substrings:"aa""b""cc"All substrings are non-overlappingOutput: ["aa", "b", "cc"] - Maximum count: 3
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
Asked in
Google 12 Facebook 8 Amazon 6
15.0K Views
Medium Frequency
~25 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen