Encode and Decode Strings
Difficulty: Medium · Pattern: Hashing · LeetCode #271
Design a Codec with encode(strs) → str (a list of strings into one string) and decode(s) → list, which restores the original list exactly. Strings may contain any characters, including #, digits, commas and empty strings. The tests check that decode(encode(strs)) == strs.
Examples
text
["lint", "code", "love", "you"] → round-trips unchanged
["", "#", "5#hi"] → round-trips unchangedHints
- Joining with a delimiter breaks if strings contain the delimiter.
- Prefix each string with its length and a separator.
Approach
Length prefixing: encode each string as len(s) + '#' + s. To decode, read digits up to the next # to get the length L, take the next L characters as the string, and repeat. This is unambiguous no matter what the strings contain, because you never search for a delimiter inside the content. (This is how many wire protocols frame messages.)
Complexity
Time: O(total length). Space: O(total length).
Python solution
class Codec:
def encode(self, strs):
return "".join(f"{len(s)}#{s}" for s in strs)
def decode(self, s):
out, i = [], 0
while i < len(s):
j = s.index("#", i)
n = int(s[i:j])
out.append(s[j + 1:j + 1 + n])
i = j + 1 + n
return outJavaScript solution
class Codec {
encode(strs) { return strs.map((s) => `${s.length}#${s}`).join(''); }
decode(s) {
const out = []; let i = 0;
while (i < s.length) {
const j = s.indexOf('#', i), n = Number(s.slice(i, j));
out.push(s.slice(j + 1, j + 1 + n)); i = j + 1 + n;
}
return out;
}
}