KatInterview

String Array Framing and Round-Trip Encoding

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstringsarraysdesign-ds

Last 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

  1. 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.
  2. Edge Cases: Empty strings "" and empty lists [] are valid inputs. [] must produce a distinct round-trip output from [""].
  3. No External Libraries: Do not rely on general object serialization libraries (e.g., json, pickle, or eval).
  4. 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^4
  • 0 <= len(strs[i]) <= 10^4
  • Total characters across all strings in strs will not exceed 10^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.