Encode and Decode Strings – Solution & Complexity
Solution Walkthrough
Step 1: Why a plain delimiter fails
- Joining with a separator like
,or#breaks as soon as one of the input strings contains that character. - Instead of scanning for an end marker inside the payload, tell the decoder up front how many characters belong to the next string.
- Joining with a separator like
Step 2: Length-prefix framing
- Encode each string
wasf"{len(w)}#{w}". Even ifwitself is"3#abc", it encodes to"5#3#abc". - When decoding at index
i, scan forward to the next#at indexj, parselength = int(s[i:j]), reads[j + 1 : j + 1 + length], and jumpi = j + 1 + length. - The decoder never inspects the payload for
#, so any character is safe.
- Encode each string
Step 3: Optimal O(n) length-prefix codec
- Both
encodeanddecodevisit each character once:O(n)time andO(n)space wherenis the total number of characters across all strings.
- Both
Step 4: Common mistakes
- Assuming lengths are single-digit (
int(s[i])) instead of parsing all digits up to#. - Confusing
[](empty list, encodes to"") with[""](one empty string, encodes to"0#"). - Searching for
#from index0instead of from indexi.
- Assuming lengths are single-digit (
Part of Blind 75 · NeetCode 150