1Question
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.
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.
Encode the list to one string, then decode it. We must get the same four words back.
The word “:” is a single character that looks like a separator. It must still come back as its own word.
A list with one empty string is not the same as an empty list. Both must survive the round trip.
Constraints
Fewer than 100 strings. The list can also be empty.
Each string has fewer than 200 characters. A string can be empty.
Even #, digits, commas and spaces can appear inside a string. So no single character is safe as a separator.
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
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:
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.
For each word, write len(word), then #, then the word. Join everything into one string.
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.
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([]))) # [''] WRONG6Optimal Solution
Write the length and a # before every word. Decode by jumping over exactly that many characters.
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)
Optimal (length prefix)
How big is the difference?
Extra characters added by the encoding (k words, each length up to 199):
| Words (k) | Separator version | Length-prefix version |
|---|---|---|
| 1 | 0 extra | at most 4 extra |
| 10 | 9 extra | at most 40 extra |
| 99 | 98 extra | at 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.