All coding questions

Encode and Decode Strings

medium
NeetCode 150stringsdesign

Problem

Design an encoder that serializes a list of arbitrary strings into one string, and a decoder that recovers the original list. The strings may contain any characters, including your delimiters.

Examples

Input: ["neet", "code", "love", "you"]
Output: decode(encode(input)) == input
Round-tripping must reproduce the original list exactly.
Input: ["", "a#b"]
Output: decode(encode(input)) == input
Empty strings and embedded delimiters must survive.

Constraints

  • 0 <= list length <= 200
  • Strings may contain any Unicode characters
Hints(tap to reveal)
  • 1. A naive separator fails when the data contains it.
  • 2. Length-prefixing each chunk removes ambiguity.
Optimal approach(spoiler)
  1. Encode each string as its length, a separator character, then the raw string.
  2. Concatenate these length-prefixed chunks.
  3. To decode, read the integer length up to the separator.
  4. Slice out exactly that many characters, then repeat from the next chunk.
  5. Length-prefixing is robust to any content in the payload.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor