Encode and Decode Strings

Medium

Problem

Design encode(list of strings) → one string, and decode(that string) → the original list. The strings may contain any character, including whatever you might choose as a delimiter.

Example 1

Input:  ["neet", "co#de", ""]
Output: decode(encode(input)) returns ["neet", "co#de", ""]

Test cases

Case 1

Input:    ["neet","co#de",""]
Expected: ["neet","co#de",""]

Case 2

Input:    []
Expected: []

Case 3

Input:    ["1#2","##","12#"]
Expected: ["1#2","##","12#"]

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Length prefix

Time O(total length)Space O(total length)

Write each string as "<length>#<string>". The decoder reads digits up to "#", then exactly that many characters — so "#" inside a string is harmless.

const encode = (strs) => strs.map((s) => s.length + '#' + s).join('');
function decode(str) {
const res = [];
let i = 0;
while (i < str.length) {
const hash = str.indexOf('#', i);
const len = Number(str.slice(i, hash));
res.push(str.slice(hash + 1, hash + 1 + len));
i = hash + 1 + len;
}
return res;
}

Joining with a delimiter breaks when a string contains the delimiter — say why you rejected it.