1. Length prefix
Prefix each string with its length and a delimiter.
result += str.length + "#" + strTyporithm · medium
Step 1 of 8 · intro card
Arrays & Hashing
Encode each string as length#string; decode by reading the length up to '#', then slicing exactly that many characters.
A plain delimiter fails when strings can contain that delimiter character.
Length-prefix encoding writes each string's length, a '#', then the raw string.
Decoding reads digits up to '#', parses the length, and slices exactly that many characters — robust to any content.
Format: length + '#' + string.
Read the length up to '#'.
Slice exactly length characters.
function encode(strs) {
let result = "";
for (const str of strs) {
result += str.length + "#" + str;
}
return result;
}
function decode(str) {
const result = [];
let i = 0;
while (i < str.length) {
let j = i;
while (str[j] !== "#") {
j += 1;
}
const length = Number(str.slice(i, j));
const word = str.slice(j + 1, j + 1 + length);
result.push(word);
i = j + 1 + length;
}
return result;
}Connect each part of the code to the concept before you type.
Prefix each string with its length and a delimiter.
result += str.length + "#" + strScan to the delimiter to read the length digits.
while (str[j] !== "#") {
j += 1;
}Convert the digits before # into a number.
const length = Number(str.slice(i, j))Take exactly length characters after the delimiter.
const word = str.slice(j + 1, j + 1 + length)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.