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 Number of Non-Overlapping Substrings INPUT String s = "aabcc" a 0 a 1 b 2 c 3 c 4 Character Ranges: 'a': first=0, last=1 'b': first=2, last=2 'c': first=3, last=4 Valid Intervals: [0,1] [2,2] [3,4] ALGORITHM STEPS 1 Find Boundaries For each char, find first and last occurrence 2 Extend Intervals Include all occurrences of chars in substring 3 Sort by End Index Greedy: prioritize shortest intervals 4 Select Non-Overlapping Pick intervals that don't overlap Greedy Selection: 0 1 2 3 4 aa b cc No overlaps - All selected! FINAL RESULT Selected Substrings: "aa" "b" "cc" ["aa", "b", "cc"] Statistics: Count: 3 substrings Total Length: 2+1+2 = 5 Minimum total length! OK - All conditions met! Key Insight: The greedy approach works by first computing valid intervals for each character (expanding to include all occurrences), then sorting by end position. Selecting the shortest non-overlapping intervals maximizes count while minimizing total length. Time Complexity: O(n) where n = string length. TutorialsPoint - Maximum Number of Non-Overlapping Substrings | Greedy - Select Shortest Valid Intervals
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