TRT
Sign in
mediumFoundationsLeetCode#length-prefixed framing#contiguous layout

Encode and decode a list of strings

Pack a list of arbitrary strings into a single contiguous byte buffer with length prefixes and decode it back without delimiter collisions.

The Runtime Theory Team1 min read
Taught inContiguous and scattered dataData either sits in one unbroken block, where an address can be computed, or in separate pieces joined by pointers, where it has to be followed. Most data structures are a choice between the two.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

in["lint", "code", "love", "you"]

out["lint", "code", "love", "you"]

in["we", "say", ":", "yes", "4#ab"]

out["we", "say", ":", "yes", "4#ab"]

in[""]

out[""]

Design an encoder that packs a list of strings (which may contain any character, including colons, hashes, newlines, or empty strings) into one contiguous string, and a decoder that reconstructs the exact original list.

Before you code

If you join strings with a delimiter like , or #, what happens when one of the strings itself contains that character? Instead of searching for a sentinel at the end of each string, store the byte length of the string right in front of it, followed by a single separator such as #. Once the decoder reads the length k before #, it jumps forward k characters in constant time without scanning for delimiters inside the payload.

Hints

  1. Format each string s as "{len(s)}#{s}" — for example, "code" becomes "4#code" and "" becomes "0#".
  2. In the decoder, keep a cursor i at the start of the current record. Scan forward until # to parse the integer length k.
  3. Slice the next k characters starting right after #, append that substring to your result list, and advance i to hash_index + 1 + k.

Production & complexity notes

When solving Encode and decode a list of strings on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Contiguous and scattered data to reinforce the underlying pattern.

What it practices

Flattening scattered pointer-based strings into a single contiguous length-prefixed buffer, from Contiguous and scattered data.

Not started

Sign in to save your learning progress.

Sign in to save