Skip to content
GKgkml.dev
← Problem set
#271MediumArrays & hashing

Encode and Decode Strings

The tell: Serialise a list of arbitrary strings so it can be split back unambiguously.

How you get there

  1. 1Any delimiter can appear inside the payload, so delimiters alone are unsafe.
  2. 2Length-prefix each string: write len, a separator, then the raw content.
  3. 3Decoding reads the length, then slices exactly that many characters — content is never parsed.

Solution

Python
def encode(strs: list[str]) -> str:
    return "".join(f"{len(s)}#{s}" for s in strs)

def decode(data: str) -> list[str]:
    out: list[str] = []
    i = 0
    while i < len(data):
        j = data.index("#", i)          # first # after i delimits the length
        length = int(data[i:j])
        out.append(data[j + 1 : j + 1 + length])
        i = j + 1 + length
    return out
Time
O(total length)
Space
O(total length)

What goes wrong

Joining on a 'rare' character fails the moment the input legitimately contains it.