Encode and Decode Strings
Medium · Arrays & Hashing
Design a way to pack a list of strings into a single string, and a matching way to unpack that string back into the original list. The strings may contain any printable characters, including ones that could be confused with a delimiter such as ':' or '#', so the scheme must be able to unambiguously reconstruct the exact original list no matter what characters appear inside the strings. Implement encode(strs) to produce the packed string, and decode(s) to recover the list from it. Correctness is judged by checking that decoding the encoded form of a list always reproduces that exact list.
Examples
Input: strs = ["neet","code","love","you"]
Output: a single packed string that decode() turns back into ["neet","code","love","you"]
Why: The encode function packs the list into one string, and decode unpacks that string back into the original list.
Input: strs = ["we","say",":","yes"]
Output: a single packed string that decode() turns back into ["we","say",":","yes"]
Why: Even though one string is just a colon, the scheme must still recover the exact original list.
Constraints
0 <= number of strings <= 300, 0 <= length of each string <= 1000, strings may contain any printable ASCII characters including delimiter-like characters such as ':' and '#'
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Encode and Decode Strings
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Encode and Decode Strings. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.