241/670

241. Encode and Decode Strings

Medium

Your service needs to ship a list of strings strs across a channel that can only carry one string. Design the two ends of that pipe:

  • encode receives the list and packs it into a single string.
  • decode receives that single string and must reconstruct exactly the original list.

The round trip decode(encode(strs)) has to reproduce strs perfectly for every possible list: strings may be empty, may contain spaces, digits, #, or any other printable character — including whatever character you were hoping to use as a separator. No information may travel outside the encoded string itself (no globals, no side channels).

The judge feeds your two functions a list, runs the full round trip, and checks the reconstruction.

Example 1:

Input: strs = ["code", "interview", "!"]

Output: ["code", "interview", "!"]

Explanation: Whatever wire format you invent, unpacking must hand back ["code", "interview", "!"] unchanged — so the printed round trip matches the input list.

Example 2:

Input: strs = ["we say #yes#", ""]

Output: ["we say #yes#", ""]

Explanation: The list is ["we say #yes#", ""]. Spaces, # characters and the trailing empty string must all survive the trip, and the count line (2) proves the empty string was not dropped.

Constraints:

  • 0 ≤ strs.length ≤ 100
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] consists of printable ASCII characters (newlines never appear inside a string).
  • All information must live inside the one encoded string — no shared state between encode and decode.

Hints:

A plain separator like a comma fails the moment a string contains a comma. Either make separators un-fakeable (escaping) or stop searching for separators entirely.

Escaping: pick an escape character e; write e+e for a literal e and e+separator for a literal separator. The decoder reads character by character and never misparses.

Length-prefixing sidesteps scanning: emit `len(s)` then a marker then the s bytes. The decoder always knows exactly how many characters to grab, so the content is never even inspected.

Check the two nasty boundary cases by hand: the empty list and a list containing only "" must encode to different strings.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: strs = ["code", "interview", "!"]

Expected output: ["code", "interview", "!"]