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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<int> PartitionLabels(string s) {
6 int[] last = new int[26];
7 for (int i = 0; i < s.Length; i++) {
8 last[s[i] - 'a'] = i;
9 }
10
11 List<int> result = new List<int>();
12 int start = 0, end = 0;
13
14 for (int i = 0; i < s.Length; i++) {
15 end = Math.Max(end, last[s[i] - 'a']);
16 if (i == end) {
17 result.Add(end - start + 1);
18 start = i + 1;
19 }
20 }
21 return result;
22 }
23}
24
This C# solution employs an integer array to store the last occurrence index of each character. The partitions are determined by the maximum of these indices over the characters currently in the partition.
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.