Design an algorithm to encode a list of strings to a single string.
This problem follows the Length Prefix Encoding pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Prefix each string with its length followed by a delimiter.
Length-prefixing is delimiter-safe — even if strings contain '#' or any character, the length tells you exactly where each string ends.
def encode(strs):
return ''.join(str(len(s)) + '#' + s for s in strs)
def decode(s):
result, i = [], 0
while i < len(s):
j = s.index('#', i)
length = int(s[i:j])
result.append(s[j+1 : j+1+length])
i = j + 1 + length
return resultPractice Encode and Decode Strings and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.
Practice this problem