Encode and Decode Strings - Problem

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

Machine 1 (sender) has the function:

string encode(vector<string> strs) { // ... your code return encoded_string; }

Machine 2 (receiver) has the function:

vector<string> decode(string s) { //... your code return strs; }

So Machine 1 does: string encoded_string = encode(strs);

And Machine 2 does: vector<string> strs2 = decode(encoded_string);

strs2 in Machine 2 should be the same as strs in Machine 1.

Implement the encode and decode methods. You are not allowed to solve the problem using any serialize methods (such as eval).

Input & Output

Example 1 — Basic Strings
$ Input: strs = ["hello", "world"]
Output: ["hello", "world"]
💡 Note: Encode to "5#hello5#world", decode reads length 5, extracts "hello", reads length 5, extracts "world"
Example 2 — Empty String
$ Input: strs = ["", "a"]
Output: ["", "a"]
💡 Note: Encode to "0#1#a", decode reads length 0 for empty string, then length 1 for "a"
Example 3 — Special Characters
$ Input: strs = ["a|b", "c#d"]
Output: ["a|b", "c#d"]
💡 Note: Encode to "3#a|b3#c#d", length prefix handles strings with delimiters correctly

Constraints

  • 1 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • strs[i] contains any possible characters out of 256 valid ASCII characters

Visualization

Tap to expand
Encode and Decode Strings ProcessInput Array"hello""world""test"ENCODEEncoded String"5#hello5#world4#test"DECODEReconstructed Array"hello""world""test"
Understanding the Visualization
1
Input
Array of strings that need to be encoded
2
Encode
Convert array to single string with length prefixes
3
Decode
Reconstruct original array from encoded string
Key Takeaway
🎯 Key Insight: Length prefixes eliminate the need for escaping special characters in strings
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen