String Array Framing and Round-Trip Encoding
StringsAuto-graded · 22 test casesLast updated
Design a robust serialization scheme that packs a list of arbitrary strings into a single string and successfully reconstructs it without ambiguity.
You are building a lightweight messaging layer that transmits lists of strings across a stream that only supports sending a single combined text message at a time.
To ensure complete accuracy, you need to convert an arbitrary list of strings into a single formatted string (encode) and subsequently parse that formatted string back into the exact original sequence of strings (decode).
Requirements
- Arbitrary Characters: Each string in the list may contain any valid character (including digits, spaces, colons, newlines, or delimiters). The encoding scheme must handle any character without conflict or ambiguity.
- Edge Cases: Empty strings
""and empty lists[]are valid inputs.[]must produce a distinct round-trip output from[""]. - No External Libraries: Do not rely on general object serialization libraries (e.g.,
json,pickle, oreval). - Consistency: The original order of elements and all duplicates must be fully preserved.
Write a function round_trip_strings(strs: List[str]) -> List[str] that performs the complete encoding and decoding pipeline and returns the decoded list of strings.
Constraints
0 <= len(strs) <= 10^40 <= len(strs[i]) <= 10^4- Total characters across all strings in
strswill not exceed10^5. - Each string
strs[i]can consist of any Unicode characters.
Examples
Example 1
Input: round_trip_strings([])
Output: []
Example 2
Input: round_trip_strings([''])
Output: ['']
Example 3
Input: round_trip_strings(['a', 'b', 'c'])
Output: ['a', 'b', 'c']
Example 4
Input: round_trip_strings(['hello', 'a:b', '', ':', '123', 'hello'])
Output: ['hello', 'a:b', '', ':', '123', 'hello']
Hints
Hint 1
Avoid using simple delimiter splitting (e.g., `,` or `:`), because strings inside the input list can contain those exact characters.
Hint 2
Consider prefixing each string's content with its length followed by a non-digit delimiter (such as length + ':').
Hint 3
The length prefix tells the decoder exactly how many subsequent characters belong to that specific string token, ignoring any delimiter-like characters inside the string body.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
When packing an arbitrary sequence of strings into a single string, relying on fixed split delimiters (like commas or colons) fails whenever the contents of a string contain that delimiter. Escape characters can resolve this, but length-prefixing is simpler, faster, and robust against all character variations.
Length-Prefixed Framing Scheme
-
Encoding:
- For each string $s$, measure its length $L = \text{len}(s)$.
- Prefix $s$ with $L$ and a sentinel separator character (e.g.,
":"). - Format:
<length>:<content>. - Concatenate all encoded elements into one combined string.
- Examples:
[]$\rightarrow$""[""]$\rightarrow$"0:"["a", "b:c"]$\rightarrow$"1:a3:b:c"
-
Decoding:
- Maintain a pointer $i$ initialized to
0. - Read characters while they are digits to extract the integer string length $L$.
- Verify and skip the
:separator. - Read exactly $L$ characters starting from the pointer position to reconstruct the original string.
- Advance the pointer by $L$ and repeat until the entire serialized string is consumed.
- Maintain a pointer $i$ initialized to
Complexity Analysis
-
Time Complexity:
- Encoder: $\mathcal{O}(N)$ where $N$ is the total length of all characters across all strings.
- Decoder: $\mathcal{O}(N)$ as each character in the string is scanned once to extract length and string payload.
- Total Time Complexity: $\mathcal{O}(N)$.
-
Space Complexity:
- Encoder: $\mathcal{O}(N)$ to construct the serialized payload.
- Decoder: $\mathcal{O}(N)$ to hold the reconstructed array of strings.
- Total Auxiliary Space Complexity: $\mathcal{O}(N)$.
Implementation
from typing import List
def round_trip_strings(strs: List[str]) -> List[str]:
def encode(values: List[str]) -> str:
return ''.join(f"{len(val)}:{val}" for val in values)
def decode(message: str) -> List[str]:
result = []
i = 0
n = len(message)
while i < n:
start = i
while i < n and message[i].isdigit():
i += 1
if i == start or i >= n or message[i] != ':':
raise ValueError("malformed encoded message")
length = int(message[start:i])
i += 1
end = i + length
if end > n:
raise ValueError("truncated encoded message")
result.append(message[i:end])
i = end
return result
return decode(encode(strs))