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
This C implementation performs a two-step traversal of the given string. Firstly, we map each character's last occurrence to create the partition scopes. In the walk-through, the size of a partition is determined when the maximum index matches the loop index, marking partition boundaries.