Algo-Sim › Arrays & Hashing

Encode and Decode Strings

Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Pack a list of strings into one string and unpack it again, with a length prefix so any character can appear inside.

Problem

Design encode, which turns a list of strings into a single string, and decode, which turns that string back into the original list. The strings may contain any character, including whatever you choose as a separator, and may be empty. decode(encode(strs)) must equal strs.

Constraints

Edge cases to test

Follow-up questions

Why not join with a separator like a comma?
Any separator can appear inside a string. Escaping works but every character must be scanned twice. A length prefix needs no escaping: O(total length).
How would you make the format binary-safe and compact?
Write each length as a fixed 4-byte integer (or a varint) before the bytes: what protocol buffers do. Same O(n), no parsing of digits.

Solution

Java

public class Codec {
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for (String s : strs) {
            sb.append(s.length()).append('#').append(s);
        }
        return sb.toString();
    }

    public List<String> decode(String s) {
        List<String> out = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            int j = i;
            while (s.charAt(j) != '#') j++;
            int len = Integer.parseInt(s.substring(i, j));
            out.add(s.substring(j + 1, j + 1 + len));
            i = j + 1 + len;
        }
        return out;
    }
}

Python

class Codec:
    def encode(self, strs):
        parts = []
        for s in strs:
            parts.append(f"{len(s)}#{s}")
        return "".join(parts)

    def decode(self, s):
        out, i = [], 0
        while i < len(s):
            j = s.index("#", i)
            length = int(s[i:j])
            out.append(s[j + 1:j + 1 + length])
            i = j + 1 + length
        return out

C++

#include <bits/stdc++.h>
using namespace std;

class Codec {
  public:
    string encode(vector<string> &strs) {
        string sb;
        for (string s : strs) {
            sb += to_string(s.size()) + '#' + s;
        }
        return sb;
    }

    vector<string> decode(string &s) {
        vector<string> out = {};
        int i = 0;
        while (i < int(s.size())) {
            int j = i;
            while (s[j] != '#')
                j++;
            int len = stoi(s.substr(i, (j) - (i)));
            out.push_back(s.substr(j + 1, (j + 1 + len) - (j + 1)));
            i = j + 1 + len;
        }
        return out;
    }
};

More Arrays & Hashing problems