← Whiteboard questions

Encode and Decode Strings

Turn a list of strings into one string and back again

DSA, Medium, Arrays & Hashing

Which structure or algorithm, and what does it cost.

Write two functions. encode(strs) turns a list of strings into one single string. decode(s) turns that string back into the same list. The strings can be empty, and they can hold any characters, including digits and the symbols you might pick as separators. The round trip decode(encode(strs)) must give back strs exactly.

Examples

Input strs = ["ab", "", "c#d"]
Output ["ab", "", "c#d"]
Why the empty string and the # inside c#d must both come back unchanged.
Input strs = []
Output []
Why an empty list encodes to an empty string and decodes back to an empty list.
Input strs = ["12#x", "#", "9"]
Output ["12#x", "#", "9"]
Why digits and # signs inside the strings must come back as text, never read as part of your format.

Constraints

Your answer must contain

Target Aim for O(N + m) time and memory for each function, where N is the total number of characters and m is the number of strings.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A separator character is risky, because the strings may hold that same character. Think about what the decoder could be told instead.

Hint 2 the approach

Store each string's length in front of the string. If the decoder knows how many characters to take, it never needs to look inside the text.

Hint 3 the key step

Write the length, then a marker that ends the number, then the string. To decode, read up to the marker, take that many characters, and continue after them.

Walkthrough

Full walkthrough brute force to best

Brute force

Join the strings with a separator such as a comma, and split on it to decode. This is simple and linear, but it breaks when a string holds the separator, and it cannot tell an empty list from a list with one empty string. For the given constraints it is wrong, not just slow.

Better method

Escape the separator inside each string (a backslash before a comma and before a backslash) and end every string with an unescaped comma. This is O(N + m) and correct, but encoder and decoder must agree on every escape rule.

Best method

Put the length of each string in front of it. Write the number of characters, then a marker such as a hash sign, then the string itself. To decode, start at position 0. Find the first marker after it, because everything before it is the length and a length has only digits. Read that many characters as the next string. Move to the position after them and repeat until the end. The marker can safely appear inside strings, because the decoder never searches inside a string, it jumps over it by the stored length. An empty string is stored as 0 and the marker, and an empty list is an empty text.

Hand trace

Run encode on ["ab", "", "c#d"]. "ab" has length 2, so it adds 2#ab. "" has length 0, so it adds 0#. "c#d" has length 3, so it adds 3#c#d. The result is 2#ab0#3#c#d. Run decode. At position 0, the first hash is at position 1, the length is 2, and the next 2 characters are ab. The position moves to 4. The first hash after it is at 5, the length is 0, so the string is empty. The position moves to 6. The first hash after it is at 7, the length is 3, and the next 3 characters are c#d. The position moves to the end, so decode returns ["ab", "", "c#d"].

Code

def encode(strs):
    return ''.join(str(len(s)) + '#' + s for s in strs)
def decode(s):
    out = []
    i = 0
    while i < len(s):
        j = s.index('#', i)
        n = int(s[i:j])
        out.append(s[j + 1:j + 1 + n])
        i = j + 1 + n
    return out

Time and memory

O(N + m) time and memory, where N is the total number of characters and m the number of strings, because each string adds its length digits and one marker. The decoder jumps over each string by its length, and it copies each character once.

Common mistakes

  • Joining with a plain separator. A string that holds the separator is split into two strings.
  • Writing the length with no marker after it. Then the digits of the length and a string that starts with a digit run together.
  • Reading the length as one digit. A string of 12 characters needs two digits, so read up to the marker.
  • Splitting the encoded text on the marker when decoding. The marker can also appear inside the strings, so jump by the length instead.

Related problems

More Arrays & Hashing problems
Encode and Decode Strings: walkthrough and Python solution