DSA AnimatorDSA animations
Encode and Decode Strings LC #271 Medium Length-Prefix Encoding
Problem

Design an algorithm to encode a list of strings to a single string and decode it back. The encoded string is transmitted over a network — it must be decodable even when individual strings contain special characters like #, ,, or any other byte.

Example 1
Input: ["hello","world"]
Encoded: "5#hello5#world"
Decoded: ["hello","world"] ✓
Example 2
Input: ["we","say",":","yes"]
Encoded: "2#we3#say1#:3#yes"
Explanation: Works even with special chars — length prefix makes it unambiguous.
Constraints: 1 ≤ strs.length ≤ 200 | 0 ≤ strs[i].length ≤ 200 | strs[i] contains any possible characters
Try Examples
Custom:
Approach
Length-prefix encoding: each word → "len#word"
Decode by reading the integer before #, then extracting exactly that many chars. No delimiter ambiguity possible.
Phase
—
Input Words
Encoded Buffer
—
length prefix
word content
Variables
phase
—
word
—
chunk
—
i
—
len
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Encode: for each word → append "len#word" to buffer
2
Result is single encoded string with all words packed
3
Decode: set i = 0; loop while i < enc.length
4
Find j = indexOf('#', i); parse len = enc[i..j]
5
Extract word = enc[j+1 .. j+1+len]; advance i = j+1+len
6
Repeat until end → return decoded list
Time
O(n)
Space
O(n)
Why This Works

A simple delimiter (comma, pipe) fails if strings contain that delimiter. Length-prefix encoding is unambiguous: parse the integer before #, then read exactly that many characters — no special character inside the word can interfere. Even strings containing # (e.g. "5#hello") decode correctly.

How to solve Encode and Decode Strings

LeetCode 271 · Medium · Strings · Pattern: Length Prefix

Why the obvious approach is slow

Joining with a separator, like a comma, breaks as soon as a word contains a comma. Escaping special characters works, but it is fiddly and easy to get wrong.

The key idea

Put the length of each word in front of it, followed by a hash. To decode, read digits up to the hash, which gives the length. Then take exactly that many characters, no matter what they are.

Remember

Length prefixes make any content safe. Read the length first, then read exactly that many characters.

Run the animation above on your own input, or watch the 1:32 video explanation of Encode and Decode Strings with a dry run and Java code.

More Strings problems