Arrays & Hashing

Length-Prefix Encoding

Encode and Decode Strings

1Question

Encode and Decode Strings

MediumLeetCode 271 ↗

Design two functions. encode turns a list of strings into one single string. decode takes that one string and gives back the exact same list.

Rules

The encoded string is sent over a network, so decode only gets the string. It can not share any other data with encode. Your code must work for any character, even the ones you wanted to use as a separator.

This is a LeetCode Premium problem (LeetCode 271). The statement above is a short version of it.

Examples
Example 1
Input: ["lint","code","love","you"]
Output: ["lint","code","love","you"]

Encode the list to one string, then decode it. We must get the same four words back.

Example 2
Input: ["we","say",":","yes"]
Output: ["we","say",":","yes"]

The word “:” is a single character that looks like a separator. It must still come back as its own word.

Example 3
Input: [""]
Output: [""]

A list with one empty string is not the same as an empty list. Both must survive the round trip.

Constraints

0 ≤ strs.length < 100

Fewer than 100 strings. The list can also be empty.

0 ≤ strs[i].length < 200

Each string has fewer than 200 characters. A string can be empty.

strs[i] contains any of the 256 valid ASCII characters

Even #, digits, commas and spaces can appear inside a string. So no single character is safe as a separator.

Follow-up

Can you write an algorithm that is stateless? That means encode and decode can not use any shared variable or memory between calls.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Length-Prefix Encoding

Write how long each piece is before the piece, so you never have to guess where it ends.

Instead of marking the end of a word with a separator, we mark its size before it. Each word becomes length + # + word:

encode(["lint", "code"]) = "4#lint4#code"

The decoder reads the number up to the first #, then takes exactly that many characters as the word. The word can contain anything, because we never scan inside it.

How to spot this pattern

  • You must pack several values into one string or byte stream and unpack them later.
  • The values can contain any character, so a separator is not safe.
  • The reader only has the final string, so the string must describe itself.
  • You see words like serialize, deserialize, encode, decode or protocol.

4Explanation

The big idea: Every word is stored as length#word. All of them are glued one after another with nothing between them.

Encode

For each word, write len(word), then #, then the word. Join everything into one string.

Decode

Keep a pointer i. Find the next # to read the length, then take that many characters. Move i past them and repeat.

Why does a # inside a word not break it? We find the first # starting at i. That one always belongs to the length, because the length is the very first thing at i. After that we jump over the word by counting characters, so we never read its inside.

Why is the empty string safe? It is written as 0#. Decode reads length 0 and takes zero characters. An empty list is the empty string "", which is different from "0#".

5Brute Force

Join the words with a separator, then split on it.

Idea

The first idea most people have is simple:

  • In encode, join all words with a separator such as #.
  • In decode, split the string on #.
  • It looks fine for ["lint", "code"], but breaks as soon as a word contains #, or when the list is empty.
Python
def encode_brute(strs):
    return "#".join(strs)            # "lint#code#love#you"


def decode_brute(s):
    return s.split("#")              # breaks if a word contains "#"


print(decode_brute(encode_brute(["lint", "code"])))   # ['lint', 'code']   OK
print(decode_brute(encode_brute(["a#b", "c"])))       # ['a', 'b', 'c']    WRONG
print(decode_brute(encode_brute([])))                 # ['']               WRONG

6Optimal Solution

Write the length and a # before every word. Decode by jumping over exactly that many characters.

Python
def encode(strs):
    out = []
    for s in strs:
        out.append(str(len(s)) + "#" + s)    # e.g. "4#lint"
    return "".join(out)


def decode(s):
    result = []
    i = 0

    while i < len(s):
        j = s.index("#", i)                  # first "#" after i ends the length
        length = int(s[i:j])                 # the number before "#"

        start = j + 1                        # the word starts right after "#"
        result.append(s[start:start + length])

        i = start + length                   # jump over the word

    return result


words = ["we", "say", ":", "yes"]
code = encode(words)
print(code)                  # 2#we3#say1#:3#yes
print(decode(code))          # ['we', 'say', ':', 'yes']
print(decode(encode([""])))  # ['']

7Time and Space Complexity

Let n be the number of items in the array.

Brute force (separator)

Time: O(n)Space: O(n)

Optimal (length prefix)

Time: O(n)Space: O(n)

How big is the difference?

Extra characters added by the encoding (k words, each length up to 199):

Words (k)Separator versionLength-prefix version
10 extraat most 4 extra
109 extraat most 40 extra
9998 extraat most 396 extra

Both are O(n) in time and space. The length-prefix version pays a few extra characters per word, and in return it is correct for every input.

8Visualization

Try:Use 1 to 5 words, up to 8 characters each, separated by commas. No commas inside a word. # is allowed.
Phase-
Current Word / Length-
Encoded Length-
"lint" "code" "love" "you"

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Encode: each word becomes len + # + word
Decode: first # from i ends the length
Then: take length chars, jump i past them