1. Last index map
Record the last position each character appears.
last[s[i]] = iTyporithm · medium
Step 1 of 8 · intro card
Greedy
Map each character's last index, then grow a partition until the scan reaches its farthest required end.
Each character must live entirely within one partition, so a partition has to reach every character's last occurrence.
First record the last index of every character.
Then scan, stretching the current end to the farthest last-index seen; close the partition when i meets end.
Precompute last index per character.
Extend end to last[s[i]].
Close when i === end.
function partitionLabels(s) {
const last = {};
for (let i = 0; i < s.length; i += 1) {
last[s[i]] = i;
}
const result = [];
let start = 0;
let end = 0;
for (let i = 0; i < s.length; i += 1) {
end = Math.max(end, last[s[i]]);
if (i === end) {
result.push(end - start + 1);
start = i + 1;
}
}
return result;
}Connect each part of the code to the concept before you type.
Record the last position each character appears.
last[s[i]] = iThe partition must reach the last occurrence of every character inside it.
end = Math.max(end, last[s[i]])When the scan reaches the current end, the partition is complete.
if (i === end)Save the partition length and start the next one.
result.push(end - start + 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText ababcbacadefegdehijhklij
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state