KatInterview

271. Encode and Decode Strings

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Length-Prefixed Encoding

This problem requires us to design a scheme to convert a list of strings into a single string (encode) and then convert it back to the original list (decode). The main challenge is that the strings can contain any of the 256 ASCII characters. This means we cannot use a simple delimiter (like a comma) to join the strings, as the delimiter itself might be part of a string, leading to ambiguity during decoding.

Solution

Encode and Decode Strings in Python

class Codec:
    def encode(self, strs: List[str]) -> str:
        """Encodes a list of strings to a single string.
        We prepend each string with its length and a delimiter '#'.
        Example: ["Hello", "World"] -> "5#Hello5#World"
        """
        # Using a list and join is more efficient in Python than repeated string concatenation.
        encoded_parts = []
        for s in strs:
            encoded_parts.append(f"{len(s)}#{s}")
        return "".join(encoded_parts)

    def decode(self, s: str) -> List[str]:
        """Decodes a single string to a list of strings.
        """
        decoded_strs = []
        i = 0
        while i < len(s):
            # Find the delimiter '#' to separate length from the string content.
            j = s.find('#', i)
            
            # Parse the length, which is the substring from current position `i` to `j`.
            length = int(s[i:j])
            
            # Extract the string using the parsed length.
            # The string starts right after '#' and has `length` characters.
            decoded_strs.append(s[j + 1 : j + 1 + length])
            
            # Move the pointer `i` to the beginning of the next encoded chunk.
            i = j + 1 + length
            
        return decoded_strs

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(strs))

Encode and Decode Strings in Java

public class Codec {

    // Encodes a list of strings to a single string.
    public String encode(List<String> strs) {
        // Using StringBuilder for efficient string concatenation.
        StringBuilder sb = new StringBuilder();
        // For each string, prepend its length and a delimiter '#'.
        // Example: {"Hello", "World"} -> "5#Hello5#World"
        for (String s : strs) {
            sb.append(s.length()).append('#').append(s);
        }
        return sb.toString();
    }

    // Decodes a single string to a list of strings.
    public List<String> decode(String s) {
        List<String> result = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            // Find the delimiter '#' to separate length from the string content.
            int j = s.indexOf('#', i);
            
            // Parse the length, which is the substring from the current position `i` to `j`.
            int length = Integer.parseInt(s.substring(i, j));
            
            // Extract the string using the parsed length.
            // The string starts right after the '#' and has `length` characters.
            result.add(s.substring(j + 1, j + 1 + length));
            
            // Move the pointer `i` to the beginning of the next encoded chunk.
            i = j + 1 + length;
        }
        return result;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(strs));

Encode and Decode Strings in C++

class Codec {
public:

    // Encodes a list of strings to a single string.
    string encode(vector<string>& strs) {
        string encoded_string = "";
        // For each string, prepend its length and a delimiter '#'.
        // Example: {"Hello", "World"} -> "5#Hello5#World"
        for (const string& s : strs) {
            encoded_string += to_string(s.length()) + '#' + s;
        }
        return encoded_string;
    }

    // Decodes a single string to a list of strings.
    vector<string> decode(string s) {
        vector<string> strs;
        int i = 0;
        while (i < s.length()) {
            // Find the position of the delimiter '#'.
            // This separates the length from the actual string content.
            size_t delimiter_pos = s.find('#', i);
            
            // Extract the length of the string, which is the substring before the '#'.
            int len = stoi(s.substr(i, delimiter_pos - i));
            
            // Extract the actual string using the parsed length.
            strs.push_back(s.substr(delimiter_pos + 1, len));
            
            // Move the index to the beginning of the next encoded chunk.
            i = delimiter_pos + 1 + len;
        }
        return strs;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.decode(codec.encode(strs));

Encode and Decode Strings in TypeScript

/**
 * Encodes a list of strings to a single string.
 */
function encode(strs: string[]): string {
    // We construct a single string by prepending each string
    // with its length and a delimiter '#'.
    // Example: ["Hello", "World"] -> "5#Hello5#World"
    let encodedString = "";
    for (const s of strs) {
        encodedString += `${s.length}#${s}`;
    }
    return encodedString;
};

/**
 * Decodes a single string to a list of strings.
 */
function decode(s: string): string[] {
    const decodedStrings: string[] = [];
    let i = 0;
    while (i < s.length) {
        // Find the delimiter '#' to separate length from the string.
        const j = s.indexOf('#', i);
        
        // Parse the length, which is the substring from current position `i` to `j`.
        const length = parseInt(s.substring(i, j));
        
        // Extract the string using the parsed length.
        // The string starts right after '#' and has `length` characters.
        const strStart = j + 1;
        const strEnd = strStart + length;
        const str = s.substring(strStart, strEnd);
        decodedStrings.push(str);
        
        // Move the pointer to the beginning of the next encoded chunk.
        i = strEnd;
    }
    return decodedStrings;
};

/**
 * Your functions will be called as such:
 * decode(encode(strs));
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.