Encode and Decode Strings

Design an algorithm to encode a list of strings to a single string.

Pattern

Length Prefix Encoding

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.

Approach

How to Solve It

Prefix each string with its length followed by a delimiter.

Key Insight

Length-prefixing is delimiter-safe — even if strings contain '#' or any character, the length tells you exactly where each string ends.

Step-by-step

  1. 1To encode: for each string, prepend its length and a delimiter (e.g. '5#hello')
  2. 2Concatenate all encoded strings
  3. 3To decode: read the length number, skip the delimiter, extract that many characters
  4. 4Repeat until the entire string is consumed

Pseudocode

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 result
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Arrays & Hashing Problems

Master this pattern with YeetCode

Practice Encode and Decode Strings and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.

Practice this problem