AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

Encode and Decode Strings

The key idea

Prefix each string with its length and a separator (len#str). The length tells the decoder exactly how many characters to read, so it never has to guess where one string ends. This is immune to any character — including the separator itself — appearing inside the data.

Problem

Design an algorithm to encode a list of strings into a single string. The encoded string is then sent over the network and decoded back into the original list of strings.

Machine 1 has a function encode that turns strs (a list of strings) into one combined string. That string travels to Machine 2, whose decode function must reconstruct the exact original list — same strings, same order, same count.

The tricky part is that each string may contain any character, including digits, spaces, or the very symbol you might want to use as a separator. Your scheme must round-trip correctly no matter what bytes appear inside the strings, and it must distinguish an empty list from a list that contains one empty string. You may not assume anything about the contents beyond the stated limits, and you should not rely on any global state shared between the two machines.

Constraints

Examples

Input: dummy_input = ["Hello","World"] Output: ["Hello","World"]
Input: dummy_input = [""] Output: [""]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems