Problem statement

https://leetcode.com/problems/encode-and-decode-strings/

Solution

When we encode, put lengths of strings in the beginning of new string with separators and finish it with other separator. For example [abc, asdf, sdgsdfg] will be encoded as 3_4_7#abcasdfsdgsdfg.

Complexity

Time and space complexity of both encode and decode is $O(m)$, where m is total lenght of strings/length of encoded string.

Code

class Codec:
    def encode(self, strs):
        return "_".join(str(len(s)) for s in strs) + "#" + "".join(strs)
        
    def decode(self, s):
        ind = s.index("#")
        lengths = [int(i) for i in s[:ind].split("_")]
        cumsum = [0] + list(accumulate(lengths))
        return [s[ind+1+x:ind+1+y] for x,y in zip(cumsum, cumsum[1:])]