Pack with copy tokens

Write codeMedium30 min

Your task

A packer rewrites a byte stream as a list of tokens. Working from the left, at each position it looks for the longest run of characters starting there that also starts at some earlier position. A copy is allowed to read characters it is itself producing, so a source beginning before the current position may run past it, which is how a long repeat of one character packs into a single token. When that longest run is 2 characters or more the packer emits a copy token of exactly that length and jumps past it. Otherwise it emits a literal token covering the single character at that position and moves on by one. Given the stream, return the length of every token the packer emits, in order. An empty stream emits nothing.

Examples

packer_token_lengths(stream: str) -> list[int]
Example 1
Inputpacker_token_lengths("aaaaa")
Output[1, 4]
Example 2
Inputpacker_token_lengths("abcabcabc")
Output[1, 1, 1, 6]
Example 3
Inputpacker_token_lengths("abcd")
Output[1, 1, 1, 1]