Typorithm · medium

Encode & Decode Strings

encode-decode-stringsarrays-hashinglength-prefixdelimiterparsing
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Encode & Decode Strings

0%

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.

01

Format: length + '#' + string.

02

Read the length up to '#'.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Length prefix

Prefix each string with its length and a delimiter.

result += str.length + "#" + str

2. Find the #

Scan to the delimiter to read the length digits.

while (str[j] !== "#") {
      j += 1;
    }

3. Parse length

Convert the digits before # into a number.

const length = Number(str.slice(i, j))

4. Slice exact chars

Take exactly length characters after the delimiter.

const word = str.slice(j + 1, j + 1 + length)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Encode & Decode Strings: Lesson & Practice · Typorithm | ApplyDjinn