InterviewPrepKit

Home / Coding / Arrays & Hashing

Encode and Decode Strings

medium Original β†—
Solving tips
  • Any fixed separator fails because payloads may contain that character; use length-prefix framing instead ('5#hello').
  • The decoder reads digits up to the '#', then jumps exactly length bytes, never inspecting the payload, so embedded digits or '#' are safe.
  • Length-prefix naturally distinguishes [] from [''] and [''] from other empties; a bare join cannot.
  • Off-by-one: the next header starts at start+length (no trailing separator); target O(total characters) for both directions.

Problem

Design a pair of functions to ship a list of strings across a network as one string:

  • encode(strs) turns a list of strings into a single string.
  • decode(s) turns that single string back into the original list, exactly.

The round trip decode(encode(strs)) must reproduce the input for any list β€” the strings may contain any characters (including whatever delimiter you were tempted to use), and may be empty. You may not stash state on the side; all information must travel inside the encoded string itself.

Examples

  • encode(["hello", "world"]) β†’ some string, e.g. "5#hello5#world" β†’ decode β†’ ["hello", "world"] β€” the exact wire format is yours to choose; only the round trip matters.
  • encode([""]) β†’ must decode back to [""], a list holding one empty string β€” and not to [].
  • encode(["a#b", "#", ""]) β†’ must survive strings that contain your delimiter characters.

Constraints

  • 0 <= strs.length <= 200, each string up to 200 characters.
  • Strings may contain any ASCII character β€” assume nothing is β€œsafe” to use as a bare separator.
  • Encode and decode should each run in O(total characters).

Think about it first

Hint 1 `",".join(strs)` breaks the moment a string contains a comma. Why does *every* fixed separator have this problem, no matter how exotic the character?
Hint 2 Two classic ways out: make the separator unmistakable by *escaping* it inside data, or remove the need to search for a separator at all by announcing, up front, how far to read.
Hint 3 Prefix each string with its length plus a sentinel, e.g. `"5#hello"`. The decoder reads digits up to `#`, then consumes exactly that many characters as payload β€” anything inside the payload, including digits and `#`, is never inspected.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.