PracticeNeetCode ↗LeetCode ↗
Design an algorithm to encode a list of strings into a single string, and decode that string back into the original list. The strings may contain any characters, including digits and whatever delimiter you choose.
#) only needs to not be a digit; it doesn't need to be rare, because it's never searched for inside the payload itself.s, append len(s), then "#", then s itself, to a growing result string.i = 0.i to find the next "#", parse the digits before it as the length.length characters after the "#" as the next decoded string, advance i past it, and repeat.Time: O(n) total characters — Space: O(n)
def encode(strs: list[str]) -> str:
encoded = ""
for s in strs:
encoded += str(len(s)) + "#" + s
return encoded
def decode(s: str) -> list[str]:
result = []
i = 0
while i < len(s):
j = i
while s[j] != "#":
j += 1
length = int(s[i:j])
result.append(s[j + 1 : j + 1 + length])
i = j + 1 + length
return resultHow the solution above works, piece by piece.
encode: for each string write len(s), a #, then the string itself. The result for the example is 4#lint4#code4#love3#you.decode keeps a position i at the start of the next length prefix.j forward to the next #; int(s[i:j]) is the length. Lengths can have several digits (e.g. 12#…), which is why we scan to # instead of reading one character.s[j + 1 : j + 1 + length] is the word. It is cut by count, so any # inside it is just data.i = j + 1 + length jumps straight to the next prefix. Both functions are O(total characters).Decoding "4#lint4#code4#love3#you":
# + word. The decoder never looks for # inside a word: it reads the length first and then takes exactly that many characters, so words may themselves contain # or digits.