You are given a string s consisting of lowercase english letters.
We want to split the string into as many substrings as possible, while ensuring that each letter appears in at most one substring.
Return a list of integers representing the size of these substrings in the order they appear in the string.
Example 1:
Input: s = "xyxxyzbzbbisl"
Output: [5, 5, 1, 1, 1]Explanation: The string can be split into ["xyxxy", "zbzbb", "i", "s", "l"].
Example 2:
Input: s = "abcabc"
Output: [6]Constraints:
1 <= s.length <= 100
You should aim for a solution with O(n) time and O(m) space, where n is the length of the string s and m is the number of unique characters in the string s.
A character has a first and last index in the given string. Can you think of a greedy approach to solve this problem? Maybe you should try iterating over one of these two indices.
We store the last index of each character in a hash map or an array. As we iterate through the string, treating each index as a potential start of a partition, we track the end of the partition using the maximum last index of the characters seen so far in the current partition. Additionally, we maintain the size of the current partition using a variable, say size.
We update the end of the current partition based on the maximum last index of the characters, extending the partition as needed. When the current index reaches the partition’s end, we finalize the partition, append its size to the output list, reset the size to 0, and continue the same process for the remaining string.
Before attempting this problem, you should be comfortable with:
We want to split the string into as many parts as possible such that each letter appears in at most one part.
The key observation is:
By knowing the last index of every character, we can greedily decide where to end each partition.
As we scan the string:
res to store partition sizessize = 0 for the current partition lengthend = 0 for the farthest index the current partition must reachi:c:end = max(end, lastIndex[c])i == end:size to ressize to 0resWhere is the length of the string and is the number of unique characters in the string .
A common mistake is trying to find the last occurrence of each character on the fly during the main traversal. This leads to O(n^2) time complexity. You must precompute the last index of every character in a first pass to achieve O(n) time.
After completing a partition (when i == end), forgetting to reset the size counter to 0 causes partition sizes to accumulate incorrectly. Each new partition must start with a fresh count.
When checking if the current index equals the end of the partition, make sure to use the correct comparison. The partition ends when i == end, not i > end or i >= end. An off-by-one error here will either split partitions prematurely or merge partitions that should be separate.