Encode and Decode Strings (LeetCode 271): Solution and Explanation
Design two functions: one turns a list of strings into a single string, and the other turns that single string back into the original list. The strings may contain any ASCII character, including the ones you might want to use as separators.
Watch it run step by step
Try your own input and write the code →Intuition
The first idea most people have is to join the strings with a delimiter such as a comma and split on it later. That breaks the moment a string contains a comma, and since the input can contain any of the 256 ASCII characters, there is no character you can safely reserve. Escaping the delimiter works, but it is fiddly and easy to get wrong.
The robust fix is to stop relying on content to mark boundaries and instead say up front how long each piece is. If the encoded form of each string is its length, then a marker character, then the string itself, the decoder never has to search inside the payload. It reads digits until it reaches the marker, converts them to a number, and then takes exactly that many characters as the string, no matter what those characters are.
The marker # can appear inside a string without causing trouble, because the decoder only looks for # while reading the length, and lengths are made of digits only. After it slices out the payload, it jumps directly to the start of the next length prefix. Empty strings work too, since they encode as 0# followed by nothing, and an empty list encodes as an empty string.
Approach: Length prefix with a separator
- To encode, loop over the strings and append
str(len(s)) + "#" + sfor each one. - To decode, keep an index
iat the start of the next length prefix. - Scan forward with
jfromiuntils[j]is#; the digits between them are the length. - Convert
s[i:j]to an integerlengthand appends[j + 1 : j + 1 + length]to the result. - Move
itoj + 1 + length, the start of the next prefix, and repeat untilireaches the end.
Step-by-step example
strs = ["lint", "c#de", ""]
- Encoding produces "4#lint" + "4#c#de" + "0#", which is "4#lint4#c#de0#".
- Decoding starts at i = 0. The first
#is at j = 1, so the length is 4 and the payload is "lint". Move to i = 6. - At i = 6, the next
#is at j = 7, so the length is 4 and the payload is "c#de". The#inside it is never examined as a separator. Move to i = 12. - At i = 12, the next
#is at j = 13, so the length is 0 and the payload is "". Move to i = 14, which is the end. - The decoded list is ["lint", "c#de", ""], identical to the input.
Code: Python, Java, C++
1class Solution:
2 def encode(self, strs: List[str]) -> str:
3 res = ""
4 for s in strs:
5 res += str(len(s)) + "#" + s
6 return res
7
8 def decode(self, s: str) -> List[str]:
9 res, i = [], 0
10 while i < len(s):
11 j = i
12 while s[j] != "#":
13 j += 1
14 length = int(s[i:j])
15 res.append(s[j + 1 : j + 1 + length])
16 i = j + 1 + length
17 return res1public class Solution {
2 public String encode(List<String> strs) {
3 StringBuilder sb = new StringBuilder();
4 for (String s : strs) {
5 sb.append(s.length()).append("#").append(s);
6 }
7 return sb.toString();
8 }
9
10 public List<String> decode(String s) {
11 List<String> res = new ArrayList<>();
12 int i = 0;
13 while (i < s.length()) {
14 int j = i;
15 while (s.charAt(j) != '#') j++;
16 int len = Integer.parseInt(s.substring(i, j));
17 res.add(s.substring(j + 1, j + 1 + len));
18 i = j + 1 + len;
19 }
20 return res;
21 }
22}1class Solution {
2public:
3 string encode(vector<string>& strs) {
4 string res = "";
5 for (const string& s : strs) {
6 res += to_string(s.length()) + "#" + s;
7 }
8 return res;
9 }
10
11 vector<string> decode(string s) {
12 vector<string> res;
13 int i = 0;
14 while (i < s.length()) {
15 int j = i;
16 while (s[j] != '#') j++;
17 int len = stoi(s.substr(i, j - i));
18 res.push_back(s.substr(j + 1, len));
19 i = j + 1 + len;
20 }
21 return res;
22 }
23};Time and space complexity
O(N)
N is the total number of characters across all strings. Each character is written once during encoding and read once during decoding, plus a few digits per string for the length.
O(N)
The encoded string and the decoded list each hold all N characters plus small length prefixes.
Other approaches
Delimiter with escaping (time O(N), space O(N))
Join strings with a separator and escape any occurrence of the separator or escape character inside the strings, then unescape while splitting. It produces readable output but needs careful handling of edge cases like a trailing escape character.
Fixed-width length header (time O(N), space O(N))
Write each length as a fixed number of bytes or characters, for example four, so no separator is needed at all. It mirrors how many binary network protocols frame messages.
Common mistakes
- Splitting the encoded string on
#, which breaks as soon as a string contains#. The decoder must use the length, not search the payload. - Assuming lengths are a single digit. Strings can be up to 200 characters, so read digits until the separator.
- Mishandling empty strings, which encode as
0#. Code that skips empty payloads or expects at least one character will lose them. - Building the encoded string with repeated concatenation in a language where that copies every time. Use a string builder or a list join in Java and C++ style code.
Frequently asked questions
Why not just use a delimiter like a comma?
Any character can appear inside the input strings, so a delimiter can be confused with content. Length prefixes tell the decoder exactly where each string ends, so the content is never misread.
What if a string contains the # character?
It does not matter. The decoder only looks for # while reading the digits of a length. Once it knows the length, it copies that many characters without inspecting them, so a # inside the payload is treated as ordinary data.
What is the time complexity of encode and decode strings?
Both functions run in O(N), where N is the total number of characters, because each character is handled a constant number of times. The length prefixes add only a few characters per string.