AlgoViz

Encode and Decode Strings

Medium

Length-prefix each string

Problem

Design encode(list of strings)->one string and decode(string)->list, so any strings (including with special characters) round-trip.

In simple words

Write each word's length and a separator before it, so decoding knows exactly where each word ends.

The idea

Any delimiter can appear inside the data, so instead write each string as its length, a separator, then the characters. Decoding reads the length, then takes exactly that many characters — which is unambiguous no matter what the strings contain.

The trick

  • Format: `<len>#<string>` repeated. The # is safe because the length tells you where it is.
  • A plain separator fails as soon as a string contains it.
  • Both directions are O(total length).

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

0
0

Step 1 of 2. Here's the example — ['neet','code'] Values: 0.

1/2
Optimal
timeO(n)spaceO(n)
1encode: for s: out += len(s) + '#' + s2decode: read number until '#', then take that many chars, repeat

Input

array
[0]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
strs = ["hello","world"]
Output:
"5#hello5#world"
Explanation:
Prefix each word with its length and a marker.

Example 2

Input:
strs = ["a","bc"]
Output:
"1#a2#bc"
Explanation:
Lengths let the decoder split safely.

Example 3

Input:
strs = [""]
Output:
"0#"
Explanation:
Even an empty string encodes cleanly.

Finished the walkthrough? Add it to your streak.