763: Partition-Labels
Medium
table of contents
This is basically just a interval partitioning question in disguise.
If you look at it closely, you basically have a maximum of 26
intervals; 1 interval spanning between the first and last instance of
each respective letter. Then, once we have each interval, we can just
merge the overlapping ones and then simply append the length of each
merged interval to the ans
array.
code
class Solution {
public:
<int> partitionLabels(string s) {
vector// storing the start & end index of each letter of the alphabet
<pair<int, int>> alphabet (26, {INT32_MAX, INT32_MAX});
vectorfor (int i = 0; i < s.size(); ++i) {
[s[i]-'a'].first = min(alphabet[s[i]-'a'].first, i);
alphabet[s[i]-'a'].second = i;
alphabet}
// order the starting and ending index of each letter
<pair<int, char>> letterIndex;
vectorfor (int i = 0; i < 26; ++i) {
if (alphabet[i].second != INT32_MAX) {
.push_back({alphabet[i].first, i});
letterIndex.push_back({alphabet[i].second, i});
letterIndex}
}
(letterIndex.begin(), letterIndex.end());
sort
// to track whether we have seen the letter or not
<int> seenAlphabet (26, 0);
vector
// to track the number of intervals we are inside of
int counter = 0;
// to track when the previous interval ennded
int previous_partition = -1;
int current_index = 0;
<int> ans;
vectorfor (int i = 0; i < letterIndex.size(); ++i) {
[letterIndex[i].second] ^= 1;
seenAlphabet// we will only see each letter twice;
// first XOR operation == 1
// second XOR operation == 0
if (seenAlphabet[letterIndex[i].second]) {
++counter;
} else {
--counter;
}
= letterIndex[i].first;
current_index if (counter == 0) {
.push_back(current_index - previous_partition);
ans= current_index;
previous_partition }
}
return ans;
}
};