Skip to content
  • Arrays & Hashing · Sheet 150

Encode and Decode Strings

LearnViaNotes @learnvianotes· 1 min read

Difficulty: Medium · LeetCode 271

Problem

Design encode/decode for a list of strings to a single string. Must handle any characters including #, |, etc.

Intuition

Length-prefix encoding: Format each string as "{length}#{content}". During decode, read the length, skip #, read exactly that many chars. No delimiter collisions possible.

Optimized Code

Python
class Codec:
    def encode(self, strs: list[str]) -> str:
        return ''.join(f'{len(s)}#{s}' for s in strs)

    def decode(self, s: str) -> list[str]:
        res, i = [], 0
        while i < len(s):
            j = s.index('#', i)
            length = int(s[i:j])
            res.append(s[j+1:j+1+length])
            i = j+1+length
        return res
C++
class Codec {
public:
    string encode(vector<string>& strs) {
        string res;
        for (const string& s : strs) res += to_string(s.size()) + "#" + s;
        return res;
    }

    vector<string> decode(string s) {
        vector<string> res;
        int i = 0;
        while (i < s.size()) {
            int j = s.find('#', i);
            int length = stoi(s.substr(i, j - i));
            res.push_back(s.substr(j + 1, length));
            i = j + 1 + length;
        }
        return res;
    }
};
Java
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> res = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            int j = s.indexOf('#', i);
            int length = Integer.parseInt(s.substring(i, j));
            res.add(s.substring(j + 1, j + 1 + length));
            i = j + 1 + length;
        }
        return res;
    }
}
JavaScript
var encode = s => s.map(w => `${w.length}#${w}`).join('');
var decode = function(s) {
    const res=[]; let i=0;
    while(i<s.length){
        const j=s.indexOf('#',i), len=parseInt(s.slice(i,j));
        res.push(s.slice(j+1,j+1+len)); i=j+1+len;
    }
    return res;
};

Encode O(n) · Decode O(n) · Space O(n)

Takeaway

Pattern: Length-Prefix Encoding — Encode variable-length data with a length prefix to avoid delimiter ambiguity. Used in HTTP/2 framing, protobuf, network protocols.

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report