Sponsored
Sponsored
This approach uses a greedy method where we determine the possible endpoints of each partition by finding the last occurrence of each character. As we iterate through the string, we expand the end of the current partition to the maximum last occurrence index of all characters seen so far. The current partition ends once the current index matches this endpoint.
Time Complexity: O(n), where n is the length of the string, because we iterate over the string a constant number of times.
Space Complexity: O(1), as the space used for storing last occurrences is constant, not dependent on input size.
1def partitionLabels(S):
2 last = {char: i for i, char in enumerate(S)}
3 j = anchor = 0
4 result = []
5
6 for i, char in enumerate(S):
7 j = max(j, last[char])
8 if i == j:
9 result.append(i - anchor + 1)
10 anchor = i + 1
11 return result
12
This Python solution stores the last occurrence of each character in a dictionary. It iterates through the string and determines the end of each partition based on the maximum last occurrence index of characters seen. It keeps track of partition sizes using a list.
Another approach involves performing two passes over the string. The first pass is used to collect the rightmost occurrence of each character, and in the second pass, we calculate the sizes of partitions while maintaining the maximum index of characters on the go.
Time Complexity: O(n) for length n of the string, taking linear scans for mapping and partitioning.
Space Complexity: O(1) since the space needed does not grow in relation to input size.
1
The JavaScript solution runs parallel with other language implementations by setting up terminal character conditions first through key storage. This seeded information is leveraged on re-iteration to decide complete segment spans of non-repeating lettering.