Encode and Decode Strings

Join a list of strings into one string and get the same list back, whatever characters the strings contain.

Write two methods. encode takes a list of strings and turns it into a single string, which can be sent over a network or saved to a file. decode takes that single string and returns the original list. The strings may contain any characters.

Example 1
Input: ["cs", "code", "love", "you"]
Output: ["cs", "code", "love", "you"]
Explanation: one possible encoding is "2#cs4#code4#love3#you".
Example 2
Input: ["we", "say", ":", "yes"]
Output: ["we", "say", ":", "yes"]
Solution

The Idea

Suppose you want to send a list of words to a friend in one text message. The natural thing is to put a comma between them: cs,code,love,you. Your friend cuts the message at every comma and gets the four words of Example 1 back.

Now suppose one of the words is itself a,b. The list ["a,b"] becomes the message a,b, and so does the list ["a", "b"]. Your friend cannot tell which list you meant. Example 2 shows that a string may even be a lone :, and the strings may contain any characters, so every possible separator can appear inside some string.

So how can decode know where a string ends, if no character is safe to mark the end? One way is to mark separators inside the text with an extra character, called escaping, but then that extra character needs marking too. A simpler way is to say how long the string is before it starts.

That is what the encoding in Example 1 does. "cs" is written as 2#cs: its length 2, a # to show where the number ends, and then the text. decode reads the 2 and takes the next two characters, whatever they are. It never searches the text for an end mark.

Look at the picture below. It shows 2#we1##3#yes, the encoding of the list ["we", "#", "yes"], one character per box. Orange boxes hold a length, grey boxes the # after it, and green boxes the text.

The string 2#we1##3#yes, one character per box at positions 0 to 11. At position 0 the length is 2, so read we. At position 4 the length is 1, so read #. At position 7 the length is 3, so read yes. The position i jumps 0, 4, 7, 12, the end.

Decoding starts at position 0. The group labelled length 2 tells it to read 2 characters after the #, which gives we and lands on position 4. There, length 1 says to read one character. That character is a #, but it is taken as text, because the length already said so. From position 7, length 3 gives yes, and position 12 is the end of the string.

The arcs at the top show the position i jumping 0, 4, 7, 12. It only ever stops at the start of a length, never inside the text. Writing each piece of data's length in front of it is called a length prefix, and many file formats and network protocols store text this way.

Solution Approach

Turning that idea into code means settling three things: how to write each string, how decode finds where a length ends, and how it moves on to the next string.

Writing each string

What exactly goes in front of a string? Its length in ordinary decimal digits, then a #. The # is needed because a length can have more than one digit. Without it, 12ab could be a length of 1 followed by 2ab, or a length of 12. With it, 12# can only mean 12.

An empty string still gets a length: "" is written as 0#, so it is not lost. An empty list gives an empty encoded string.

Finding where a length ends

Why is the first # after the current position always the end of the length? Because decode only stops at the start of a length, and a length is made of digits only. A # inside the text never gets in the way, because the jump goes over the whole text without looking at it. In the picture, the # at position 6 is skipped this way.

Moving to the next string

Where does the next string start? Right after the text just read. If the # is at position hash and the length is len, the text fills positions hash + 1 up to hash + len, so the next length starts at hash + 1 + len. When that position reaches the end of the encoded string, every string has been read.

Java Solution

The methods encode and decode work in these steps:

  1. In encode, create a StringBuilder called sb. For each string s in the list, append s.length(), a # and s itself. Return sb.toString().
  2. In decode, create an empty list, result, and set the position i to 0. A while loop runs as long as i is before the end of the encoded string.
  3. Inside the loop, find the end of the length with s.indexOf('#', i), the first # at or after i, and keep it in hash. Turn the digits between i and hash into the number len with Integer.parseInt.
  4. Add the len characters after the # to result, then set i to hash + 1 + len, the start of the next length.
  5. When the loop ends, return result.

The main method runs both examples, the list from the picture, a list with empty strings and texts full of digits and #, and an empty list. Its last line shows, for comparison, what a plain separator does.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EncodeAndDecodeStrings {

    // Each string is written as "<length>#<text>", so any character may appear in the text
    public static String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for (String s : strs) {
            sb.append(s.length()).append('#').append(s);
        }
        return sb.toString();
    }

    public static List<String> decode(String s) {
        List<String> result = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            int hash = s.indexOf('#', i);     // the length ends at the first '#'
            int len = Integer.parseInt(s.substring(i, hash));
            result.add(s.substring(hash + 1, hash + 1 + len));
            i = hash + 1 + len;               // jump straight past the text
        }
        return result;
    }

    public static void main(String[] args) {
        List<String> a = List.of("cs", "code", "love", "you");
        System.out.println(encode(a));
        System.out.println(decode(encode(a)));

        List<String> b = List.of("we", "say", ":", "yes");
        System.out.println(decode(encode(b)));

        List<String> c = List.of("we", "#", "yes");
        System.out.println(encode(c) + " -> " + decode(encode(c)));

        List<String> d = List.of("", "12#ab", "a#b", "");
        System.out.println(encode(d) + " -> " + decode(encode(d)).equals(d));

        System.out.println("empty list -> \"" + encode(List.of()) + "\" -> "
            + decode(encode(List.of())));

        // a plain separator, for comparison: "a#b" and "c" come back as three strings
        String joined = String.join("#", List.of("a#b", "c"));
        System.out.println(joined + " split on # -> " + Arrays.toString(joined.split("#")));
    }
}

Running it prints:

Output
2#cs4#code4#love3#you
[cs, code, love, you]
[we, say, :, yes]
2#we1##3#yes -> [we, #, yes]
0#5#12#ab3#a#b0# -> true
empty list -> "" -> []
a#b#c split on # -> [a, b, c]

2#cs4#code4#love3#you is the encoding from Example 1, and the line below it is the same four words decoded again. The : of Example 2 comes back untouched, and 2#we1##3#yes from the picture decodes to [we, #, yes].

Look at 0#5#12#ab3#a#b0#. The string 12#ab looks just like a length of 12, but decode never reads it as one. It reads 5# first and takes the five characters 12#ab as text. The two empty strings are the 0# at each end, and true means the decoded list equals the original. The empty list encodes to "", and decoding that gives [], because the loop never runs.

The last line is the comma problem again, with # as the separator. Joining a#b and c gives a#b#c, and splitting it returns three strings, [a, b, c], instead of the two that went in.

The original implementation, EncodeAndDecodeStrings.java, is on GitHub.

Complexity

Both methods go through the encoded string once, encode while building it and decode while reading it. So the cost grows with its length, N: the total length of the strings, plus a few digits and a # for each one.

  • Time: O(N) for each method. encode appends every character once. decode scans only the digits of each length with indexOf, and copies each text once with substring, so every character is handled a fixed number of times.
  • Space: O(N). The StringBuilder in encode holds the encoded string, and the list from decode holds the original strings, whose total length is less than N.

For another problem that turns strings into a different form and back, see Encode and Decode Tiny URL.