15% off all plans & roadmaps Use code

See plans

Encode and Decode Strings

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 <= 200
  • 0 <= 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 0000 does 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.

View on LeetCode

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.

Watch the pattern animation

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.
Design (General/Specific) pattern infographic for Encode and Decode Strings

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

  1. In encode, create an empty output buffer.
  2. For each string s in order, convert len(s) to text and left-pad it with zeros to width 4.
  3. Append the padded length, then s itself, to the buffer.
  4. Return the buffer as one string.
  5. In decode, set i = 0 and create an empty result list.
  6. While i < len(s), parse s[i:i+4] as an integer n and add 4 to i.
  7. Append s[i:i+n] to the result and add n to i.
  8. Return the result list.

Dry run

Encode ["", "abc", "", "xyz", "12345", ""]. Each row appends a header and the content.

StepStringLengthHeaderAppendedBuffer so far
1""0000000000000
2abc300030003abc00000003abc
3""00000000000000003abc0000
4xyz300030003xyz00000003abc00000003xyz
5123455000500051234500000003abc00000003xyz000512345
6""00000000000000003abc00000003xyz0005123450000

The final buffer is 00000003abc00000003xyz0005123450000, which is the expected output.

Decode that string. Here i is the read position.

StepiHeader readnContent cutResult so far
1000000""[""]
2400033abc["", "abc"]
31100000""["", "abc", ""]
41500033xyz["", "abc", "", "xyz"]
5220005512345["", "abc", "", "xyz", "12345"]
63100000""["", "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

TimeO(N)
SpaceO(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

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. Then 1 followed by 23 and 12 followed by 3 look identical. Pad to a fixed width, or add a separator after the number.
  • Reading the header with the wrong width in decode, such as s[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 i stays at the start of the digits and the content slice includes the length. Add the header width to i before slicing the content.
  • Skipping empty strings in encode, for example if not s: continue. The decoded list then loses entries and its length changes. Always write the 0000 header, even for empty strings.
  • Using split on 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 as 0000, decoded as a list with one empty string, not an empty list.
  • All strings empty, such as ["", "", ""]. Encoded as 000000000000, decoded as three empty strings.
  • A string that is all digits, such as ["12345"]. Encoded as 000512345. 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 i reaches 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

Practise it