Encode and Decode Strings
Encode and Decode Strings is a medium arrays & hashing problem solved with the string basics pattern.
The best approach, optimal (length prefix), runs in O(L + k) time and O(L + k) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from escaping with a separator up.
Problem
Design a Codec with two methods that let a list of strings travel as one single string.
encode(strs)takes a list of strings and returns one string.decode(s)takes a string made byencodeand returns the original list: the same strings, in the same order.
The strings may hold any printable character, so no character is safe to use as a plain separator. encode and decode run on different Codec objects, so the encoded string must carry all the information. Do not use any built-in serialization or library escaping routine; write the format yourself.
The judge checks decode(encode(strs)) and expects exactly strs back.
Examples
Example 1
- Input
strs = ["code", "is", "fun"]- Output
["code", "is", "fun"]- Why
- encode turns the three words into one string, for example "4#code2#is3#fun". decode reads that string back and returns the same three words in the same order.
Example 2
- Input
strs = ["a#b", "3#", "", "/"]- Output
["a#b", "3#", "", "/"]- Why
- The words may contain any symbol, digits and even look like a length header, and some may be empty. The format must still bring every one of them back exactly.
Example 3
- Input
strs = []- Output
[]- Why
- An empty list must come back as an empty list, not as a list holding one empty string.
Constraints
0 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]may contain any printable ASCII character (codes 32 to 126), including spaces, digits,#,/and,.- encode and decode are called on two different Codec objects, so no state may be shared between them.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Escaping with a separator | O(L) | O(L) |
| Optimal (length prefix) | O(L + k) | O(L + k) |
1Escaping with a separator
O(L)L is the total number of characters. Each character is copied once while encoding and read once while decoding.O(L)The encoded string is at most about twice L plus two characters per string, and the decoded list holds L characters.Use / as an escape character. Inside the data, write every / as //. After each string, write the pair /, as its end mark. While decoding, a / followed by another / is one real / of the data, and a / followed by , ends the current string. A plain character is just data. Because every / of the data was doubled, the end mark can never be confused with data.
- encode: for each string, copy its characters, writing // for every /, then append /,.
- decode: scan the text with an index i and build the current string.
- If text[i] is / and text[i + 1] is /, add one / and move i by 2.
- If text[i] is / and text[i + 1] is ,, the current string is complete: add it to the result, start a new one and move i by 2.
- Otherwise add text[i] and move i by 1.
class Codec {
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
for (char ch : s.toCharArray()) {
if (ch == '/') sb.append("//");
else sb.append(ch);
}
sb.append("/,");
}
return sb.toString();
}
public List<String> decode(String s) {
List<String> out = new ArrayList<>();
StringBuilder cur = new StringBuilder();
int i = 0;
while (i < s.length()) {
char ch = s.charAt(i);
if (ch == '/' && s.charAt(i + 1) == '/') {
cur.append('/');
i += 2;
} else if (ch == '/') {
out.add(cur.toString());
cur.setLength(0);
i += 2;
} else {
cur.append(ch);
i++;
}
}
return out;
}
}class Codec:
def encode(self, strs: List[str]) -> str:
parts = []
for s in strs:
for ch in s:
if ch == '/':
parts.append('//')
else:
parts.append(ch)
parts.append('/,')
return ''.join(parts)
def decode(self, s: str) -> List[str]:
out = []
cur = []
i = 0
while i < len(s):
ch = s[i]
if ch == '/' and s[i + 1] == '/':
cur.append('/')
i += 2
elif ch == '/':
out.append(''.join(cur))
cur = []
i += 2
else:
cur.append(ch)
i += 1
return outclass Codec {
public:
string encode(vector<string>& strs) {
string sb;
for (const string& s : strs) {
for (char ch : s) {
if (ch == '/') sb += "//";
else sb += ch;
}
sb += "/,";
}
return sb;
}
vector<string> decode(string s) {
vector<string> out;
string cur;
size_t i = 0;
while (i < s.size()) {
char ch = s[i];
if (ch == '/' && s[i + 1] == '/') {
cur += '/';
i += 2;
} else if (ch == '/') {
out.push_back(cur);
cur.clear();
i += 2;
} else {
cur += ch;
i++;
}
}
return out;
}
};class Codec {
encode(strs) {
const parts = [];
for (const s of strs) {
for (const ch of s) {
if (ch === '/') parts.push('//');
else parts.push(ch);
}
parts.push('/,');
}
return parts.join('');
}
decode(s) {
const out = [];
let cur = [];
let i = 0;
while (i < s.length) {
const ch = s[i];
if (ch === '/' && s[i + 1] === '/') {
cur.push('/');
i += 2;
} else if (ch === '/') {
out.push(cur.join(''));
cur = [];
i += 2;
} else {
cur.push(ch);
i++;
}
}
return out;
}
}2Optimal (length prefix)
O(L + k)L is the total number of characters and k the number of strings. Each data character is copied once each way, and each header is a few digits long.O(L + k)The encoded string holds the data plus a short header per string, and the decoded list holds the data again.Write each string as its length, then #, then the string itself: "code" becomes 4#code. The decoder reads digits up to the first #, which gives the length, and then takes exactly that many characters without looking at them. Data can contain # or digits freely, because the decoder only ever searches for # inside a header, never inside the data.
- encode: for each string s, append s.length(), then #, then s.
- decode: start with i = 0. While i is inside the text:
- Find j, the first # at or after i. The number between i and j is the length len.
- The string is the len characters right after the #: from j + 1 up to j + 1 + len. Add it to the result.
- Move i to j + 1 + len, the start of the next header.
class Codec {
public String encode(List<String> strs) {
StringBuilder sb = new StringBuilder();
for (String s : strs) {
sb.append(s.length()).append('#').append(s);
}
return sb.toString();
}
public List<String> decode(String s) {
List<String> out = new ArrayList<>();
int i = 0;
while (i < s.length()) {
int j = s.indexOf('#', i);
int len = Integer.parseInt(s.substring(i, j));
out.add(s.substring(j + 1, j + 1 + len));
i = j + 1 + len;
}
return out;
}
}class Codec:
def encode(self, strs: List[str]) -> str:
parts = []
for s in strs:
parts.append(str(len(s)) + '#' + s)
return ''.join(parts)
def decode(self, s: str) -> List[str]:
out = []
i = 0
while i < len(s):
j = s.index('#', i)
length = int(s[i:j])
out.append(s[j + 1:j + 1 + length])
i = j + 1 + length
return outclass Codec {
public:
string encode(vector<string>& strs) {
string sb;
for (const string& s : strs) {
sb += to_string(s.size()) + "#" + s;
}
return sb;
}
vector<string> decode(string s) {
vector<string> out;
size_t i = 0;
while (i < s.size()) {
size_t j = s.find('#', i);
int len = stoi(s.substr(i, j - i));
out.push_back(s.substr(j + 1, len));
i = j + 1 + len;
}
return out;
}
};class Codec {
encode(strs) {
const parts = [];
for (const s of strs) {
parts.push(s.length + '#' + s);
}
return parts.join('');
}
decode(s) {
const out = [];
let i = 0;
while (i < s.length) {
const j = s.indexOf('#', i);
const len = parseInt(s.substring(i, j), 10);
out.push(s.substring(j + 1, j + 1 + len));
i = j + 1 + len;
}
return out;
}
}Edge cases to test
- An empty list versus a list with one empty string (they must encode differently)
- Empty strings in the middle or at the end of the list
- Strings that contain the separator or escape character
- Strings that start with digits, so they look like a length header
- Strings longer than 9 characters, so the length has more than one digit
Hints
Hint 1
Joining with a comma fails as soon as a string contains a comma. Whatever separator you choose, a string can contain it, so you need a way to tell a real separator apart from data.
Hint 2
One fix is escaping: double every escape character inside the data, so a single one followed by something else can only be a separator.
Hint 3
A cleaner fix is to write each string's length in front of it, then a marker such as #. The decoder reads the number, skips the marker and takes exactly that many characters, so it never looks inside the data.
FAQ
What is the best time complexity for Encode and Decode Strings?
Optimal (length prefix) runs in O(L + k) time and O(L + k) extra space. L is the total number of characters and k the number of strings. Each data character is copied once each way, and each header is a few digits long.
Which pattern does Encode and Decode Strings use?
It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Minimum Changes To Make Alternating Binary String, Rotate String.
Is there a brute force solution for Encode and Decode Strings?
Yes. Escaping with a separator takes O(L) time and O(L) space. Use / as an escape character.
Which edge cases should I test for Encode and Decode Strings?
An empty list versus a list with one empty string (they must encode differently); Empty strings in the middle or at the end of the list; Strings that contain the separator or escape character; Strings that start with digits, so they look like a length header; Strings longer than 9 characters, so the length has more than one digit.