Frame payloads with lengths, preserve empty and hash-containing strings, and distinguish trusted character decoding from validated and byte-counted formats.
QuestionInterview executionCoding practice
Published ·15 min read·Core·Mixed
ML breadth · active recall
Practice before you read
8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.
A decimal length before # makes each payload boundary explicit, even when the payload contains # or is empty.
Problem trace
Count the payload, preserve empty entries, and resume at the next header
Read it this way:Read the decimal length, skip its header delimiter, then consume exactly that many Python characters. The interior hash belongs to a#b. The zero-length record consumes no payload but emits an empty list entry; its header still advances the cursor. An empty stream has no records, unlike 0#. Repeat from the next header. A byte protocol needs byte lengths instead. Does the zero-length record advance past its header?
Sources and provenance
Full interview answer 15 min read
Encode a list of arbitrary strings into one string and recover the exact original list.
Problem
Input.encode_strings receives a list of Python strings; decode_strings receives a complete string produced by the encoder.
Output. Encoding returns one string; decoding returns the original list, including every character and every list entry.
Rules. Preserve order, repeated entries, empty strings, and punctuation that could also appear in the encoding format.
An empty list and a list containing one empty string must remain distinguishable.
Do not modify the input list. The reference decoder assumes trusted, complete encoder output.
Example. Encoding then decoding ["hello", "", "a#b", "hello"] must recover that exact four-item list.
Under the reference format, [] encodes as "", while [""] encodes as "0#".
Picture
Write each record as length#text:
Input text
Record
Payload range in complete data
"lint"
4#lint
[2:6]
"#"
1##
[8:9]
""
0#
[11:11]
Complete data is 4#lint1##0#, with eleven character positions.
Before each decode loop, index starts the next header. separator finds that header’s #; length reads its preceding decimal digits.
Move index after the delimiter, consume exactly length characters, then advance by that length.
At index six, header 1# ends at index eight. The next # is one payload character, not another delimiter.
Length zero still consumes a header, appends one empty string, and advances to the next record or end.
Arbitrary strings, including empty strings and delimiter characters, must be concatenated and later recovered without escaping ambiguity.
Keep true
At the start of each decode loop, index points to the first decimal length digit. After locating # and consuming exactly length payload characters, index points to the next length or end of data.
Reuse it
Prefix each record with a parseable size in the same unit used for slicing. Byte transport must count encoded bytes, while complete-input validation and streaming state require additional checks.
The first input string has length 4, so encoding emits 4#lint. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is 1## unambiguous? Why does 0# append an empty string rather than nothing?
Reference drawing
Problem trace
Count the payload, preserve empty entries, and resume at the next header
Execution trace
Input and goalConvert a list of any strings into one string and recover the exact list.
Encode lintThe first input string has length 4, so encoding emits 4#lint.
encode item 0lint0#1""2
emitted4#lint
encode item 0
0
emitted
4#lint
index 0
lint
Encode #The second payload is the delimiter character itself, but its length prefix makes 1## unambiguous.
lint0encode item 1#1""2
emitted4#lint1##
encode item 1
0→1
emitted
4#lint→4#lint1##
Encode the empty stringThe empty payload has length 0, so it emits 0# and the complete data is 4#lint1##0#.
lint0#1encode item 2""2
emitted4#lint1##0#
encode item 2
1→2
emitted
4#lint1##→4#lint1##0#
Decode length 4At index 0, separator=1 and length=int(data[0:1])=4. Move index to 2.
Arbitrary strings, including empty strings and delimiter characters, must be concatenated and later recovered without escaping ambiguity.
Keep true
At the start of each decode loop, index points to the first decimal length digit. After locating # and consuming exactly length payload characters, index points to the next length or end of data.
Reuse it
Prefix each record with a parseable size in the same unit used for slicing. Byte transport must count encoded bytes, while complete-input validation and streaming state require additional checks.
The first input string has length 4, so encoding emits 4#lint. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is 1## unambiguous? Why does 0# append an empty string rather than nothing?
Read it this way:Read the decimal length, skip its header delimiter, then consume exactly that many Python characters. The interior hash belongs to a#b. The zero-length record consumes no payload but emits an empty list entry; its header still advances the cursor. An empty stream has no records, unlike 0#. Repeat from the next header. A byte protocol needs byte lengths instead. Does the zero-length record advance past its header?
Code
def encode_strings(strings: list[str]) -> str: return "".join(f"{len(text)}#{text}" for text in strings)def decode_strings(data: str) -> list[str]: strings = [] index = 0 while index < len(data): separator = data.index("#", index) length = int(data[index:separator]) index = separator + 1 strings.append(data[index : index + length]) index += length return strings
Let E count encoded characters, including headers. With bounded-size header arithmetic, scanning and copying take O(E) work and output space.
This decoder is an inverse, not a validator. decode_strings("3#ab") returns ["ab"] because Python permits short slices.
Missing delimiters or invalid numbers can raise exceptions. Signed headers are not rejected explicitly.
Change Validation or Units
Start from decode_strings. Two adjustable parts are input trust and the unit counted by each header.
Reject incomplete or malformed records.
New task: Return None for a missing decimal header or insufficient payload.
Picture and change: Keep the record-start cursor. Require ASCII decimal digits and check the endpoint before slicing.
Code: Complete replacement for a complete input, not partial network chunks:
def decode_checked(data): strings = [] index = 0 while index < len(data): separator = data.find("#", index) if separator < 0: return None header = data[index:separator] if not header.isascii() or not header.isdecimal(): return None try: length = int(header) except ValueError: return None start = separator + 1 end = start + length if end > len(data): return None strings.append(data[start:end]) index = end return strings
Check:3#ab and -1#a return None. 4#lint1##0# returns ["lint","#",""].
Leading zeros remain valid: 00# encodes one empty record. Conversion failures return None.
Use when: Encoder provenance is absent. Production still needs header, record-count, payload, and total-size caps before costly conversion or allocation.
Valid bounded-header parsing costs O(E). Rejected input can require scanning its complete malformed header.
Count transport bytes.
New task: Frame UTF-8 payload bytes instead of Python code points.
Picture and change: Encode each payload first, count bytes, and slice bytes before decoding text.
Python literal
Code points
UTF-8 bytes
"\u00e9"
1
2
"#"
1
1
Code: This complete helper changes both sides and decodes only its own encoder output.
Strings must be UTF-8 encodable.
def utf8_framed_roundtrip(strings): payloads = [text.encode("utf-8") for text in strings] data = b"".join( str(len(payload)).encode("ascii") + b"#" + payload for payload in payloads ) strings = [] index = 0 while index < len(data): separator = data.index(b"#", index) length = int(data[index:separator]) start = separator + 1 strings.append(data[start:start + length].decode("utf-8")) index = start + length return strings
Check:["\u00e9","#",""] roundtrips unchanged. Counting one code point but slicing one byte would split the first payload incorrectly.
Use when: The external medium measures bytes. Work and storage scale with encoded bytes, under bounded-header assumptions.
Rebuild the Boundary
What must survive when a chunk ends inside a payload?
Answer: The parse phase, remaining payload size, and partial data. Chunk boundaries are not record boundaries.
Neither format provides authentication, normalization, corruption recovery, or a streaming parser.