15% off all plans & roadmaps Use code
See plansEncode and Decode Strings
- LeetCode 271
- Medium
- Design Patterns
- Design (General/Specific)
Updated
TL;DR: Pack a list of strings into one string and recover it exactly, even with empty strings and any ASCII character. Write a fixed-width length before each string, and the decoder always knows where to cut.
Problem
You are given a list of strings strs. Each string can contain any of the 256 ASCII characters, including special characters, and can be empty.
Design two methods:
encode(strs)turns the list into a single string.decode(s)turns that single string back into the original list.
The encoded string must hold everything needed to rebuild the list exactly, including empty strings and strings full of symbols. You may not use built-in serialization helpers such as eval.
Example 1
Input: ["", "abc", "", "xyz", "12345", ""] Output: "00000003abc00000003xyz0005123450000" (the encoded string; decode of it returns the original list)
Constraints
1 <= strs.length <= 2000 <= strs[i].length <= 200- Each
strs[i]may contain any ASCII character.
Constraints that matter
- Strings can hold any ASCII character, so no single character is a safe separator. A delimiter-based format needs escaping, and escaping adds cases to get wrong.
- Each string has at most 200 characters, so its length fits in 3 digits. A fixed width of 4 digits is enough and removes the need for a separator after the number.
- Strings can be empty, so the format must give an empty string a visible record. A length of
0000does that. - At most 200 strings of 200 characters each means about 40,000 characters in total. A linear pass is fast, but quadratic string building is still worth avoiding as a habit.
- No built-in serialization is allowed, so you must define the format and the parser yourself.
Hints
Hint 1
This is a design problem.
Hint 2
Before each string, write its length as a zero-padded 4-digit number.
Solution
Intuition
This is a design problem. You are not searching for an answer, you are defining a format that a decoder can read without guessing. The decoder needs to know one thing at each step: where the current string ends.
Picture a shipping box where every item has a fixed-size label on top giving its length. The label is the 4-digit header, the item is the string, and the unpacker reads the label, takes exactly that much, and never opens the item to see what is inside.
The tempting answer is a separator such as # or ,. The input can contain any character, so some input will contain your separator. Join ["a#b", "c"] with # and splitting returns three pieces instead of two.
You can patch this with escape rules, but then the decoder becomes a state machine. Every escape character needs its own escape.
The fix is to stop searching for the end and store it up front. Write the length of each string before the string. The decoder reads the length, then copies exactly that many characters without looking at what they are.
Content never gets interpreted, so no character can confuse the parser. This is called length-prefixing.
One more detail removes the last ambiguity. If the length is written with a variable number of digits, you need a marker after it, or 1 followed by 23 looks like 12 followed by 3.
Padding every length to exactly 4 digits makes the header a fixed size. The decoder always reads 4 characters, parses a number, and then reads that many characters of content. With lengths up to 200, four digits is always enough.
The example output in this problem uses this exact layout: 0000 for an empty string, 0003abc for abc, and so on.
Worked example
Input: strs = ["", "abc", "", "xyz", "12345", ""] Output: "00000003abc00000003xyz0005123450000" Explanation: Each string gets a 4-digit zero-padded length in front of it. The empty strings become 0000, abc becomes 0003abc, xyz becomes 0003xyz, and 12345 becomes 0005 followed by 12345. Joined in order, these pieces give the output above. Decoding reads four digits, cuts that many characters, and repeats until the string ends.

Solution pattern
Design (General/Specific)
Part of Design Patterns
Approach 1: Fixed-width length prefixOptimalDesign (General/Specific)
Before each string, write its length as a zero-padded 4-digit number. Then write the string itself. The decoder reads 4 characters, parses them as a length n, copies the next n characters, and moves on.
The common alternative is joining with a delimiter. That fails whenever the data contains the delimiter, and escaping fixes it only by adding a second rule that the decoder must track character by character. Length-prefixing avoids the problem entirely. The content is never scanned for special characters, so there is nothing to escape.
A fixed width matters. With a variable-width number you would need a separator such as # after it. With 4 digits you always know the header is exactly 4 characters long, and a string that starts with digits cannot be mistaken for part of the header.
Why it is correct. The decoder's index always starts at the first character of a header, because the encoder wrote each header followed by exactly that many characters. Each decode step moves the index by 4 plus the parsed length, which is exactly the size the encoder wrote for that string. By induction, the index lands on every header boundary in order, so every string comes back in its original order. Content is never inspected, so no character inside a string can shift where the next header sits.
Steps
- In
encode, create an empty output buffer. - For each string
sin order, convertlen(s)to text and left-pad it with zeros to width 4. - Append the padded length, then
sitself, to the buffer. - Return the buffer as one string.
- In
decode, seti = 0and create an empty result list. - While
i < len(s), parses[i:i+4]as an integernand add 4 toi. - Append
s[i:i+n]to the result and addntoi. - Return the result list.
Dry run
Encode ["", "abc", "", "xyz", "12345", ""]. Each row appends a header and the content.
| Step | String | Length | Header | Appended | Buffer so far |
|---|---|---|---|---|---|
| 1 | "" | 0 | 0000 | 0000 | 0000 |
| 2 | abc | 3 | 0003 | 0003abc | 00000003abc |
| 3 | "" | 0 | 0000 | 0000 | 00000003abc0000 |
| 4 | xyz | 3 | 0003 | 0003xyz | 00000003abc00000003xyz |
| 5 | 12345 | 5 | 0005 | 000512345 | 00000003abc00000003xyz000512345 |
| 6 | "" | 0 | 0000 | 0000 | 00000003abc00000003xyz0005123450000 |
The final buffer is 00000003abc00000003xyz0005123450000, which is the expected output.
Decode that string. Here i is the read position.
| Step | i | Header read | n | Content cut | Result so far |
|---|---|---|---|---|---|
| 1 | 0 | 0000 | 0 | "" | [""] |
| 2 | 4 | 0003 | 3 | abc | ["", "abc"] |
| 3 | 11 | 0000 | 0 | "" | ["", "abc", ""] |
| 4 | 15 | 0003 | 3 | xyz | ["", "abc", "", "xyz"] |
| 5 | 22 | 0005 | 5 | 12345 | ["", "abc", "", "xyz", "12345"] |
| 6 | 31 | 0000 | 0 | "" | ["", "abc", "", "xyz", "12345", ""] |
After step 6, i is 35, which equals the length of the encoded string, so the loop stops. The result is the original list. Note that 12345 starts with digits, yet the decoder never confuses it with a header, because it cuts exactly 5 characters after reading 0005.
Complexity
| Time | O(N) |
|---|---|
| Space | O(N) |
Let N be the total number of characters across all strings, and k the number of strings. Encode copies each character once and writes one 4-character header per string, so it does O(N + k) work. Decode moves i forward on every step, never goes back, and copies each character once, so it is also O(N + k). Since k is at most 200 and every header has constant size, both are O(N); space is O(N) for the output, with O(1) auxiliary space beyond the builder.
PythonTested in our runner
from typing import List, Optional
class Solution:
def encode(self, strs: List[str]) -> str:
parts = []
for s in strs:
# 4-digit zero-padded length, then the raw string
parts.append(f"{len(s):04d}")
parts.append(s)
return "".join(parts)
def decode(self, s: str) -> List[str]:
res = []
i = 0
while i < len(s):
n = int(s[i:i + 4]) # fixed-width header
i += 4
res.append(s[i:i + n])
i += n
return res
JavaTested in our runner
import java.util.*;
class Solution {
public String encode(String[] strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
// 4-digit zero-padded length, then the raw string
sb.append(String.format("%04d", s.length()));
sb.append(s);
}
return sb.toString();
}
public List<String> decode(String s) {
List<String> res = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int n = Integer.parseInt(s.substring(i, i + 4));
i += 4;
res.add(s.substring(i, i + n));
i += n;
}
return res;
}
}
C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string encode(vector<string>& strs) {
string out;
for (const string& s : strs) {
string len = to_string(s.size());
// pad the length to 4 digits
out += string(4 - len.size(), '0') + len;
out += s;
}
return out;
}
vector<string> decode(string s) {
vector<string> res;
size_t i = 0;
while (i < s.size()) {
int n = stoi(s.substr(i, 4));
i += 4;
res.push_back(s.substr(i, n));
i += n;
}
return res;
}
};
JavaScriptTested in our runner
/**
* @param {string[]} strs
* @return {string}
*/
var encode = function(strs) {
const parts = [];
for (const s of strs) {
// 4-digit zero-padded length, then the raw string
parts.push(String(s.length).padStart(4, '0'));
parts.push(s);
}
return parts.join('');
};
/**
* @param {string} s
* @return {string[]}
*/
var decode = function(s) {
const res = [];
let i = 0;
while (i < s.length) {
const n = parseInt(s.substring(i, i + 4), 10);
i += 4;
res.push(s.substring(i, i + n));
i += n;
}
return res;
};
GoTested in our runner
import (
"fmt"
"strconv"
"strings"
)
func encode(strs []string) string {
var sb strings.Builder
for _, s := range strs {
// 4-digit zero-padded length, then the raw string
sb.WriteString(fmt.Sprintf("%04d", len(s)))
sb.WriteString(s)
}
return sb.String()
}
func decode(s string) []string {
res := []string{}
i := 0
for i < len(s) {
n, _ := strconv.Atoi(s[i : i+4])
i += 4
res = append(res, s[i:i+n])
i += n
}
return res
}
C#Tested in our runner
using System.Text;
public class Solution {
public string encode(string[] strs) {
var sb = new StringBuilder();
foreach (var s in strs) {
// 4-digit zero-padded length, then the raw string
sb.Append(s.Length.ToString("D4"));
sb.Append(s);
}
return sb.ToString();
}
public List<string> decode(string s) {
var res = new List<string>();
int i = 0;
while (i < s.Length) {
int n = int.Parse(s.Substring(i, 4));
i += 4;
res.Add(s.Substring(i, n));
i += n;
}
return res;
}
}
Common mistakes
- Joining with a delimiter, as in
"#".join(strs), and splitting on it later. Any input that contains#breaks the split, so write the length before each string instead. - Writing the length without padding, as in
str(len(s)) + s. Then1followed by23and12followed by3look identical. Pad to a fixed width, or add a separator after the number. - Reading the header with the wrong width in
decode, such ass[i:i+3]after encoding with 4 digits. The two sides must agree. Use one shared constant for the width. - Forgetting to advance past the header, so
istays at the start of the digits and the content slice includes the length. Add the header width toibefore slicing the content. - Skipping empty strings in
encode, for exampleif not s: continue. The decoded list then loses entries and its length changes. Always write the0000header, even for empty strings. - Using
spliton the encoded string to find content, or scanning the content for digits. Content must be copied by count only, never inspected.
Edge cases
[""], a single empty string. Encoded as0000, decoded as a list with one empty string, not an empty list.- All strings empty, such as
["", "", ""]. Encoded as000000000000, decoded as three empty strings. - A string that is all digits, such as
["12345"]. Encoded as000512345. The decoder cuts exactly 5 characters, so the digits are data. - Strings containing the characters you might pick as delimiters, such as
["a#b", "/:"]. Both decode intact because content is never parsed. - A string of the maximum length 200. Its header is
0200, which still fits in 4 digits. - A single list of 200 strings. The decoder loop runs 200 times and ends exactly when
ireaches the string length.
Follow-ups interviewers ask
- What if string lengths could exceed 9999?
- A 4-digit width would overflow. Either widen the header, for example 10 digits or a 4-byte binary integer, or use a variable-width number followed by a separator such as
#. The decoder then reads digits up to the separator and parses them. The separator is safe because it is only searched for in the header, never inside content. - Why not use a delimiter with escaping?
- It can be made correct, for example by doubling the escape character and ending every string with an escape-colon pair. But the decoder has to inspect every character of content and track whether the previous one was an escape. Length-prefixing never looks inside the content, so it has fewer cases and fewer bugs, and decode can copy whole slices at once.
- How would you handle non-ASCII or binary data?
- Count length in the unit you will slice by, such as bytes. Encode to bytes first, write a byte length, and slice a byte buffer on decode. Mixing character counts with byte offsets is the usual bug here, because one character can be several bytes. The same prefix idea still works unchanged.
Encode and Decode Strings FAQ
What is the time complexity of Encode and Decode Strings?
Both encode and decode run in O(N), where N is the total number of characters across all strings. Encode copies each character once and adds one fixed-size header per string. Decode moves a pointer forward once per string and copies each character once. Space is O(N) for the output.
Why use a length prefix for Encode and Decode Strings?
Because strings can contain any character, no separator is safe. A length prefix tells the decoder exactly how many characters to copy, so it never has to look for an end marker. The content can hold digits, #, or anything else without confusing the parser.
How do I solve Encode and Decode Strings in Python?
In encode, build each piece as f"{len(s):04d}" + s and join them. In decode, loop with an index: parse int(s[i:i+4]), add 4 to the index, slice that many characters, and add the length to the index. The steps above do this and work with empty strings.
Can Encode and Decode Strings be solved in O(1) extra space?
Not really. The encoded string and the decoded list must hold every character, so O(N) output space is unavoidable. Beyond the output, the algorithm uses only an index and a counter, so auxiliary space is O(1) if you write into a builder and ignore its size.
Is LeetCode 271 the same as Decode String (LeetCode 394)?
No. LeetCode 394 decodes patterns such as 3[a2[c]] using a stack and repeats. LeetCode 271 asks you to design both directions of a format for a list of strings. They share the word decode and little else.
Can I use JSON for Encode and Decode Strings?
The problem forbids built-in serialization, and using it would skip the point of the exercise. In an interview, write the length-prefix format by hand. It takes a few lines and shows you can design a protocol.
Asked at
See which companies ask this — Pro
Related problems
- LRU Cache · same technique: Design (General/Specific)
- Min Stack · same technique: Design (General/Specific)
- Time Based Key-Value Store · same technique: Design (General/Specific)
- Detect Squares · same technique: Design (General/Specific)
- Design Circular Queue · same technique: Design (General/Specific)
- Find Median from Data Stream · next harder, same pattern
- Implement Trie (Prefix Tree) · same pattern: Design Patterns
- Design Add and Search Words Data Structure · same pattern: Design Patterns
- Extra Characters in a String · same pattern: Design Patterns
- Design Hit Counter · same pattern: Design Patterns