Problem Description
Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that do not overlap and contain all occurrences of each character within them. If there are multiple solutions with the same number of substrings, return the one with the minimum total length.
Key Insights
- Substrings must include all occurrences of any character they contain.
- The substrings cannot overlap, meaning they must be disjoint.
- A greedy approach can be used to maximize the number of substrings while minimizing their total length.
- The solution must account for the last occurrence of each character to determine valid substring boundaries.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1), since we are only using a fixed amount of additional space regardless of the input size.
Solution
The solution involves two main steps:
- Determine Boundaries: For each character in the string, find the first and last occurrence. This helps in defining the boundaries of the substrings.
- Greedy Selection: Iterate through the string, and for each potential substring defined by the previous step, check if it can be included in the final result without overlapping with previously selected substrings. Select substrings based on their boundaries while ensuring they do not overlap.