Partition s into as many pieces as possible so that each letter appears in at most one piece. Return the sizes of the pieces, in order.
Record each letter's last index. Scan left to right, stretching the current piece's end to the last index of every letter seen; when i reaches that end, cut.
1function partitionLabels(s: string): number[] {2const last = new Map<string, number>();3[...s].forEach((c, i) => last.set(c, i));4const res: number[] = [];5let start = 0, end = 0;6for (let i = 0; i < s.length; i++) {7end = Math.max(end, last.get(s[i])!);8if (i === end) { res.push(end - start + 1); start = i + 1; }9}10return res;11}
Record each letter's last index.
Space: play/pause · ←/→: step