Reversible String List Serializer
StringsAuto-graded · 21 test casesLast updated
Tests whether a candidate can design a lossless encode/decode round-trip for arbitrary strings without relying on a fixed delimiter character.
Reversible String List Serializer
You need to pack a list of strings into a single string and then recover the original list exactly — including empty strings and strings that contain any character imaginable (colons, newlines, null bytes, emoji, you name it).
Your Task
Implement a function serialize_strings(strings) that:
- Encodes the input list into one string.
- Decodes that string back to the original list.
- Returns the recovered list.
Internally you will write two helpers — an encoder and a decoder — but the graded function is just the round-trip:
def serialize_strings(strings: List[str]) -> List[str]:
...
Why a Plain Separator Won't Work
If you join strings with , or | and then split on it, you break the moment any string contains that character. You cannot reserve a "safe" separator, because the input strings are unconstrained.
The Right Approach: Length-Prefix Framing
Instead of marking where strings end, tell the decoder how many characters to read. For each string s, write its character count followed by a fixed marker, then the string verbatim:
<length><marker><payload>
Because the decoder already knows how long the payload is before it starts reading it, it never has to scan inside the payload for a boundary. The marker character can appear freely inside any string — the decoder never looks for it there.
Example (using <length>:<payload> framing):
| Input list | Encoded blob |
|---|---|
["hi", ""] | 2:hi0: |
["3:x"] | 3:3:x |
[] | `` (empty string) |
Notice the third row: an empty input list encodes to an empty blob. A list containing one empty string encodes to "0:" — these two cases must be distinct.
Constraints
0 ≤ len(strings) ≤ 2000 ≤ len(strings[i]) ≤ 200strings[i]may contain any Unicode character, including digits, colons, newlines, null bytes, or characters that look like length prefixes- The round-trip must be exact:
decode(encode(strings)) == stringsfor every valid input - An empty list and a list containing one empty string are different inputs and must produce different blobs
Examples
Example 1
Input: serialize_strings(['hello', 'world'])
Output: ['hello', 'world']
Example 2
Input: serialize_strings(['', 'a:b', 'x\\ny'])
Output: ['', 'a:b', 'x\\ny']
Example 3
Input: serialize_strings([])
Output: []
Hints
Hint 1
Before writing any code, ask: what information does the decoder need at each step so it never has to inspect the payload content to find a boundary?
Hint 2
A length prefix puts that information up front. For each string, write its length (as a decimal number), then a fixed single-character marker, then the raw string. On decode, read digits until the marker, parse the length L, then take exactly the next L characters as the payload — no scanning, no ambiguity.
Hint 3
Watch the two tricky edge cases: an empty list should encode to an empty string, and a list containing a single empty string should encode to something non-empty (e.g. '0:'). Make sure your decoder loop terminates correctly when the blob is empty and that it handles a zero-length payload without skipping anything.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why separators fail
Any fixed delimiter character — comma, pipe, newline — can appear inside the strings themselves, making it impossible to distinguish a real boundary from data. Escaping works but is fiddly. The cleaner path is to make boundaries implicit in the structure rather than the content.
Length-prefix framing
For every string s, write len(s) as a decimal number, then a single colon, then the raw characters of s:
{length}:{payload}
The decoder's rule is simple:
- From the current position, read forward until the next colon — that gives the length
L. - Take exactly the next
Lcharacters as the payload. - Advance past the payload and repeat.
The decoder never searches inside a payload for a boundary, so a colon (or any other character) inside a string is always consumed as data, never misread as a header.
Correctness argument
The scheme is correct by induction on the number of strings. The invariant is: at the start of each loop iteration, i points to the first character of a length field, or i == len(blob) and the list is exhausted.
- Base case:
i = 0. Either the blob is empty (input was[]) or position 0 begins the first length field. - Inductive step:
blob.find(":", i)locates the colon that terminates the current length field. Parsingblob[i:j]as an integer givesL. The payload is exactlyblob[j+1 : j+1+L], copied verbatim fromencode. The next length field starts atj+1+L, so the invariant holds.
Every step is forced with no lookahead into payloads, so decode(encode(xs)) == xs for any xs.
Edge cases
| Input | Encoded blob | Notes |
|---|---|---|
[] | "" | Empty blob; decoder loop never runs |
[""] | "0:" | Non-empty blob; decoder reads length 0 and slices empty payload |
["3:x"] | "3:3:x" | The colon inside the payload is never inspected |
["a", "", "b"] | "1:a0:1:b" | Empty string in the middle works naturally |
The [] vs [""] distinction is automatically preserved: the empty list produces an empty blob, while a list containing one empty string produces "0:".
Complexity
Let N be the total character count across all strings and k be the number of strings.
- Encode: O(N + k) time. Parts are collected in a list and joined once; repeated
+=would be O(N²) and should be avoided. Space is O(N + k) for the output. - Decode: O(N + k) time. Each character is touched a constant number of times: one
findscan per header and one slice per payload. Space is O(N) for the output list.
Full solution
from typing import List
def encode(strings: List[str]) -> str:
# For each string, prefix it with its character count and a colon.
# The decoder reads digits up to the first colon, parses the length L,
# then slices exactly L characters — so the colon in the header is never
# confused with colons inside the payload.
parts = []
for s in strings:
parts.append(f"{len(s)}:{s}")
return "".join(parts)
def decode(blob: str) -> List[str]:
result = []
i = 0
total = len(blob)
while i < total:
# Find the colon that ends the current length field.
j = blob.find(":", i)
if j == -1:
raise ValueError(f"malformed blob: no colon found after position {i}")
length = int(blob[i:j])
if length < 0:
raise ValueError(f"negative length at position {i}")
start = j + 1
end = start + length
if end > total:
raise ValueError(
f"truncated payload: need {length} chars at {start}, "
f"but blob ends at {total}"
)
result.append(blob[start:end])
i = end
return result
def serialize_strings(strings: List[str]) -> List[str]:
return decode(encode(strings))