CodeArchon

mediumArrays & HashingGoogleAmazon

Dispatch Packet Bundler

A dispatcher must bundle a list of messages into a single transmission string and the receiver must be able to recover the exact original list — any character can appear in a message.

Design a pair of functions `encode(messages) → string` and `decode(string) → messages[]` such that `decode(encode(messages))` reproduces the original list exactly. Messages may contain any ASCII characters.

Choose approach

Hello
0
World
1
Setencoded chunks
empty
1/4
Narrationstep 1 of 4

Each message is prefixed with its length and a '#'. That way the decoder knows exactly how many characters to read.

1def encode(strs: list[str]) -> str:
2 return "".join(f"{len(s)}#{s}" for s in strs)
3
4
5def decode(data: str) -> list[str]:
6 out, i = [], 0
7 while i < len(data):
8 j = data.index("#", i)
9 n = int(data[i:j])
10 out.append(data[j + 1 : j + 1 + n])
11 i = j + 1 + n
12 return out
Variables
phase=encode
encoded=""

How to think about it

  1. You cannot use a plain delimiter (like ',') — messages may already contain any character.
  2. Give each message a self-describing frame: length + separator + payload.
  3. Encoder: for each message, append `${len}#${msg}` to the output.
  4. Decoder: at each position, read digits until '#', take that many characters as the next message, advance past them.
  5. No ambiguity — length tells the decoder exactly where every message ends.

Edge cases to catch in interview

  • Empty messages produce `0#` chunks — still unambiguous.
  • Messages containing '#' or digits are safely transported.
  • Empty input list → empty encoded string.

Examples

Example 1"5#Hello5#World"
{"messages":["Hello","World"],"values":["Hello","World"]}
Example 2"0#"
{"messages":[""],"values":[""]}
Example 3"1#a2#bc2##d"
{"messages":["a","bc","#d"],"values":["a","bc","#d"]}

Length prefix is unambiguous even with '#' inside messages.

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed