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.
1var partitionLabels = function(s) {
2 let last = {};
3 for (let i = 0; i < s.length; i++) {
4 last[s[i]] = i;
5 }
6
7 let result = [];
8 let start = 0, end = 0;
9
10 for (let i = 0; i < s.length; i++) {
11 end = Math.max(end, last[s[i]]);
12 if (i === end) {
13 result.push(end - start + 1);
14 start = i + 1;
15 }
16 }
17 return result;
18};
19
In this JavaScript solution, we map each character to its last occurrence and use this information to identify partition endpoints. The sizes of the partitions are added to the result array as they are determined.
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
In Python, this approach establishes lookup dictionary for last-found indices, followed by a wrap extending these as necessary to determine segment cut points, leading to length registration. The segments are computed end-to-end.