Encode and Decode Strings
Master this topic with zero to advance depth.
Encode and Decode Strings
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Visual Representation
Input: ["hello", "world"]
Encoding: length + '#' + string
"hello" -> "5#hello"
"world" -> "5#world"
Result: "5#hello5#world"
Decoding: Read length, skip '#', read N chars.Examples
Level I: Simple Delimiter (Risk: Collision)
Intuition
Join strings with a semicolon or other delimiter. This fails if a string itself contains the delimiter.
Detailed Dry Run
["a;b", "c"] -> "a;b;c" -> Decodes to ["a", "b", "c"] (Error!)
Level II: Length + Separator (Standard)
Intuition
Prefix each string with its length followed by a special character (e.g., '#'). When decoding, read the length, skip '#' and take that many characters.
Detailed Dry Run
["leet", "code"] -> "4#leet4#code" Read 4, skip #, read 'leet'. Read 4, skip #, read 'code'.
Level III: Optimal Solution (Base64 Encoding / Escaping)
Intuition
To handle any characters including delimiters and lengths, use an escaping mechanism or standard Base64 encoding. Alternatively, use a fixed-width length prefix (e.g., 4 bytes) for true binary safety.
Detailed Dry Run
Input: ["3#a", "b"] Encoding: Escape # as ##. Use # as delimiter. Result: "3##a#b#" Decoding: Unescape ## back to #.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.