<p>You are given a string <code>s</code>. We want to partition the string into as many parts as possible so that each letter appears in at most one part.</p>

<p>Note that the partition is done so that after concatenating all the parts in order, the resultant string should be <code>s</code>.</p>

<p>Return <em>a list of integers representing the size of these parts</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;ababcbacadefegdehijhklij&quot;
<strong>Output:</strong> [9,7,8]
<strong>Explanation:</strong>
The partition is &quot;ababcbaca&quot;, &quot;defegde&quot;, &quot;hijhklij&quot;.
This is a partition so that each letter appears in at most one part.
A partition like &quot;ababcbacadefegde&quot;, &quot;hijhklij&quot; is incorrect, because it splits s into less parts.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;eccbbbbdec&quot;
<strong>Output:</strong> [10]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 500</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    vector<int> partitionLabels(string s) {
        // Step 1: Store the first and last occurrence of each character
        vector<pair<int, int>> v(26, {-1, -1});  // Initialize for 26 characters ('a' to 'z')
        for (int i = 0; i < s.length(); i++) {
            if (v[s[i] - 'a'].first == -1) {
                v[s[i] - 'a'].first = i;  // First occurrence of character
                v[s[i] - 'a'].second = i; // Initialize last occurrence as same for now
            } else {
                v[s[i] - 'a'].second = i; // Update last occurrence
            }
        }
        
        // Step 2: Remove unused characters (-1, -1) and sort by first occurrence
        vector<pair<int, int>> intervals;
        for (auto& p : v) {
            if (p.first != -1) { // Only consider characters that appear in the string
                intervals.push_back(p);
            }
        }
        sort(intervals.begin(), intervals.end());
        
        // Step 3: Merge intervals and find partition sizes
        vector<int> result;
        int start = intervals[0].first, end = intervals[0].second;
        
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i].first > end) {  // Non-overlapping interval, close the current partition
                result.push_back(end - start + 1);  // Size of the partition
                start = intervals[i].first;  // Start a new partition
                end = intervals[i].second;
            } else {  // Overlapping interval, extend the current partition
                end = max(end, intervals[i].second);
            }
        }
        
        // Add the last partition
        result.push_back(end - start + 1);
        
        return result;
    }
};

8300