← Back to DSA Animator
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.