BackendML

Encode and Decode Strings

Medium2 min read
The Encode and Decode Strings problem asks us to design an algorithm that can convert a list of strings into a single encoded string and then reconstruct the original list of strings from that encoded representation.

Problem

Design an algorithm to encode a list of strings to a single string and then decode that string back into the original list of strings.

The encoding must preserve the boundaries between strings so that the original strings can be reconstructed correctly, even when they contain special characters.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

strs = ["hello", "world"]

Encoded

5#hello5#world

Decoded

["hello", "world"]

Solution

This solution uses Length Prefix Encoding. For each string, we store its length followed by a delimiter and then the actual string.

For example, "hello" becomes "5#hello". The length prefix tells us exactly how many characters belong to the current string. This makes the encoding safe even if the string itself contains the delimiter character.

During decoding, we first find the delimiter to determine the length of the next string. We then read exactly that many characters and add the extracted string to the result. We repeat this process until the entire encoded string has been processed.
import java.util.ArrayList;

class Solution { 
    public String encode(String arr[]) { 
        String separator = "#"; 
        StringBuilder sb = new StringBuilder(); 
        for (String str : arr) { 
            sb.append(str.length()); 
            sb.append(separator); 
            sb.append(str); 
        } 
        return sb.toString(); 
    } 

    public ArrayList<String> decode(String s) { 
        ArrayList<String> list = new ArrayList<>(); 
        int i = 0; 
        
        while (i < s.length()) {
            // Find where the delimiter '#' is located for the current string
            int j = i;
            while (s.charAt(j) != '#') {
                j++;
            }
            
            // Extract the length of the string accurately (even if it has multiple digits)
            int length = Integer.parseInt(s.substring(i, j));
            
            // The actual string starts right after '#' and spans for 'length' characters
            int startOfStr = j + 1;
            int endOfStr = startOfStr + length;
            
            list.add(s.substring(startOfStr, endOfStr));
            
            // Move the pointer 'i' to the beginning of the next encoded segment
            i = endOfStr;
        } 
        return list; 
    } 
}

Complexity

During encoding, every character from every string is processed once. Therefore, the time complexity is O(n), where n is the total number of characters across all strings.

During decoding, every character in the encoded string is processed once, resulting in O(n) time complexity.

The encoded string and decoded result require space proportional to the total input size, so the extra space complexity is O(n).

Comments

No comments yet. Ask a question or share what helped.