CodingNodes / Arrays & Hashing / Encode and Decode Strings System design Space play · ←→ step · R restart

Problem

Design a class Codec that can turn a list of strings into one string and back again, so the list can be sent over a network as a single message.

  • encode(strs) takes a list of strings and returns a single string.
  • decode(s) takes that single string and returns the original list, exactly.

The strings may contain any characters, including digits, #, spaces, or nothing at all. The codec must not keep any state between calls: decode only sees the string that encode produced. In the examples below, decode is given the encoded string written out in full, so you can see both the encoding and the round trip.

Constraints

  • 0 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] may contain any ASCII character
  • encode and decode must not share state

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Encoding copies each character once, and decoding scans each character of the encoded string once (n is the total number of characters).

Space: The output holds every character plus a short length and a hash for each string.

Write each string as length#string. To decode, read digits up to the first # to learn the length, then take exactly that many characters. Any # inside a string is skipped because we count instead of searching, so the scheme is unambiguous for every possible input.