← DSA
MEDIUM

Encode and Decode Strings

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.

Example

Input strs = ["lint","code","love","you"]
Output "4#lint4#code4#love3#you"

Key Pointers

Step-by-Step Analysis

  1. Encode: for each string s, append len(s), then "#", then s itself, to a growing result string.
  2. Decode: start at i = 0.
  3. Scan forward from i to find the next "#", parse the digits before it as the length.
  4. Read exactly length characters after the "#" as the next decoded string, advance i past it, and repeat.

Complexity

Time: O(n) total characters — Space: O(n)

Code

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 result

Code Explanation

How the solution above works, piece by piece.

  1. encode: for each string write len(s), a #, then the string itself. The result for the example is 4#lint4#code4#love3#you.
  2. decode keeps a position i at the start of the next length prefix.
  3. Move 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.
  4. s[j + 1 : j + 1 + length] is the word. It is cut by count, so any # inside it is just data.
  5. i = j + 1 + length jumps straight to the next prefix. Both functions are O(total characters).

Visual Walkthrough

Decoding "4#lint4#code4#love3#you":

Encoded string with length prefixes and payloads40#1l2i3n4t546#7c8o9d10e11412#13l14o15v16e17318#19y20o21u22i=0"lint"i=6"code"i=12"love"i=18"you"read digits up to "#" → length, take that many chars, jump i past them
Each word is stored as length + # + 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.
length digitsword characters

Video Explanation

NeetCode — Encode and Decode Strings, LeetCode 271