763. Partition Labels
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Greedy
- Time
- O(n)
- Space
- O(1)
Standard Solution (C++)
SummarySplit a string into as many parts as possible so that each letter appears in only one part, and return the sizes of those parts.
Approach
Key idea: A part must extend at least to the last occurrence of every character it contains. Track the farthest last-occurrence seen and cut when the scan reaches it.
Steps:
- Record the last index of each character.
- Scan left to right, expanding the current part end to the max last-index of seen characters.
- When the current index equals the part end, close the part and record its length.
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> last(26, 0);
for (int i = 0; i < (int)s.size(); ++i) last[s[i] - 'a'] = i;
vector<int> result;
int start = 0, end = 0;
for (int i = 0; i < (int)s.size(); ++i) {
end = max(end, last[s[i] - 'a']);
if (i == end) {
result.push_back(end - start + 1);
start = i + 1;
}
}
return result;
}
}; Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.