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.
1#include <vector>
2#include <string>
3using namespace std;
4
5vector<int> partitionLabels(string s) {
6 vector<int> last(26, 0);
7 int len = s.size();
8
9 for (int i = 0; i < len; ++i) {
10 last[s[i] - 'a'] = i;
11 }
12
13 vector<int> result;
14 int start = 0, end = 0;
15
16 for (int i = 0; i < len; ++i) {
17 end = max(end, last[s[i] - 'a']);
18 if (i == end) {
19 result.push_back(end - start + 1);
20 start = i + 1;
21 }
22 }
23 return result;
24}
25
This C++ solution follows the same logic as in C: store the last occurrence of each character in an array, iterate through the string to decide where each partition should end, and store the size of each partition in the result vector.
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
The JavaScript solution runs parallel with other language implementations by setting up terminal character conditions first through key storage. This seeded information is leveraged on re-iteration to decide complete segment spans of non-repeating lettering.