Example 1
- Input
- strs = ["lint", "code", "love", "you"]
- Output
- ["lint", "code", "love", "you"]
One valid encoding is 4#lint4#code4#love3#you, which decodes back to the original list.
Pack a list of strings into one string, then recover the same strings in the same order. Length fields preserve empty strings and characters that could otherwise be mistaken for separators.
Implement encode(strs) to produce one string and decode(encoded) to recover the original list, including its order, empty strings, and every character. The encoded representation is your choice; the output shown in the examples is the decoded list.
Do not delegate the task to a built-in serialization method such as eval. The decoder receives valid output from the matching encoder, so malformed-message validation is outside this exercise. The sender and receiver must work independently; do not keep the original list in shared state.
0 <= strs.length < 1000 <= strs[i].length < 200One valid encoding is 4#lint4#code4#love3#you, which decodes back to the original list.
The format must survive : inside a string, so bare joining on a delimiter character is not enough.
The chunk encoding is 0#3#a#b5#12|,:. After reading each length, the decoder consumes exactly that many characters, preserving the empty first string, the embedded #, and the punctuation.
Both approaches encode an empty list as an empty string. A list containing one empty string has a length field, so it remains distinguishable.
A separator alone cannot tell data from boundaries: joining ["a#b", "c"] with # looks like three strings. Send the size as well. In Example 1, 4#lint means read the length 4 up to #, then take exactly four characters. Any # inside those four characters is data. Zero is a useful length too: 0# preserves one empty string, while no chunks represents an empty list.
Reveal Length Header: intuition, complexity, and code
[] encodes as an empty string. One empty string [""] encodes as 0| with the header approach or 0# with chunks; neither is an empty list.["", "", ""] must preserve three entries; zero-length slices do not mean the decoder should stop.["123", "#", "|", ","] round-trips unchanged. Multi-digit lengths must be read up to the marker, not as one digit.j + 1 + length, even when length is zero.["", "a#b"] and explain why the embedded marker is never interpreted. Both approaches are linear; chunk prefixes are marked optimal for their simpler incremental decoding, rather than an asymptotic improvement.When arbitrary data can contain a separator, length framing separates boundary information from contents. Read a header, then consume exactly the declared amount; always agree on whether length counts characters, code units, or bytes.