Q30: Encode and Decode Strings
Design an algorithm to encode a list of strings to a single string and decode that single string back to the original list of strings.
Length-Prefix String Serialization
function encode(strs) {
return strs.map(s => `${s.length}#${s}`).join('');
}
function decode(str) {
const result = [];
let i = 0;
while (i < str.length) {
let j = i;
while (str[j] !== '#') j++;
const length = parseInt(str.slice(i, j), 10);
i = j + 1;
result.push(str.slice(i, i + length));
i += length;
}
return result;
}
const encoded = encode(['lint', 'code', 'love', 'you']);
console.log(encoded); // '4#lint4#code4#love3#you'
console.log(decode(encoded)); // ['lint', 'code', 'love', 'you']💡 Encoding formats strings as
length#string. Decoding locates #, parses integer length, and slices exact character byte segments safely.Key Takeaways
- Prefix each string with its character length followed by a delimiter (e.g.
4#code). - Avoids parsing errors caused by delimiter characters appearing inside original string content.
Knowledge Check
Why is length-prefixing preferable to simple character delimiting (e.g. comma separation)?