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.
1import java.util.ArrayList;
2import java.util.List;
3
4public class PartitionLabels {
5 public List<Integer> partitionLabels(String s) {
6 int[] last = new int[26];
7 int length = s.length();
8
9 for (int i = 0; i < length; i++) {
10 last[s.charAt(i) - 'a'] = i;
11 }
12
13 List<Integer> result = new ArrayList<>();
14 int start = 0, end = 0;
15
16 for (int i = 0; i < length; i++) {
17 end = Math.max(end, last[s.charAt(i) - 'a']);
18 if (i == end) {
19 result.add(end - start + 1);
20 start = i + 1;
21 }
22 }
23 return result;
24 }
25}
26
This Java solution works by recording the last seen position of each character, then iterating through the string to determine partition endpoints. The partition size is added to the result list whenever a partition endpoint is reached.
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.