Encode and Decode Strings – Solution & Complexity

Solution Walkthrough

  1. 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.
  2. Step 2: Length-prefix framing

    • Encode each string w as f"{len(w)}#{w}". Even if w itself is "3#abc", it encodes to "5#3#abc".
    • When decoding at index i, scan forward to the next # at index j, parse length = int(s[i:j]), read s[j + 1 : j + 1 + length], and jump i = j + 1 + length.
    • The decoder never inspects the payload for #, so any character is safe.
  3. Step 3: Optimal O(n) length-prefix codec

    • Both encode and decode visit each character once: O(n) time and O(n) space where n is the total number of characters across all strings.
    def encode_and_decode(strs: list[str]) -> list[str]:
        def encode(items: list[str]) -> str:
            return "".join(f"{len(s)}#{s}" for s in items)
    
        def decode(s: str) -> list[str]:
            res: list[str] = []
            i = 0
            while i < len(s):
                j = s.index("#", i)
                length = int(s[i:j])
                start = j + 1
                res.append(s[start : start + length])
                i = start + length
            return res
    
        return decode(encode(strs))
  4. 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 index 0 instead of from index i.

FAQ