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.
1using System.Collections.Generic;
public class Solution {
public IList<int> PartitionLabels(string s) {
int[] lastIndexes = new int[26];
for (int i = 0; i < s.Length; i++) {
lastIndexes[s[i] - 'a'] = i;
}
IList<int> partitionSizes = new List<int>();
int start = 0, end = 0;
for (int i = 0; i < s.Length; i++) {
end = Math.Max(end, lastIndexes[s[i] - 'a']);
if (i == end) {
partitionSizes.Add(end - start + 1);
start = i + 1;
}
}
return partitionSizes;
}
}
The C# rendition manages a map for final index locations much like previous solutions. As the string reiterates, division points calculated on the last alignment offer partition sizing additions to storage near conclusion of each viable segment.