Encode and Decode Strings
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Arrays & Hashing.
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
Input: ["hello", "world"]
Output: ["hello", "world"]
Approach 1
Level I: Simple Delimiter (Risk: Collision)
Intuition
Join strings with a semicolon or other delimiter. This fails if a string itself contains the delimiter.
⏱ O(N)💾 O(N)
Detailed Dry Run
["a;b", "c"] -> "a;b;c" -> Decodes to ["a", "b", "c"] (Error!)
Approach 2
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.
⏱ O(N)💾 O(N)
Detailed Dry Run
["leet", "code"] -> "4#leet4#code"
Read 4, skip #, read 'leet'.
Read 4, skip #, read 'code'.
Approach 3
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.
⏱ O(N)💾 O(N)
Detailed Dry Run
Input: ["3#a", "b"]
Encoding: Escape # as ##. Use # as delimiter.
Result: "3##a#b#"
Decoding: Unescape ## back to #.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.