InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Encode and Decode Strings

medium Original ↗ 00:00

Problem

Design two functions that encode a list of strings into a single string and decode it back:

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

decode(encode(strs)) must reproduce the input for any list. The strings may contain any characters, including any delimiter you might choose, and may be empty. All information must travel inside the encoded string; you may not store state elsewhere.

Examples

  • encode(["hello", "world"]) produces some string, e.g. "5#hello5#world", and decode returns ["hello", "world"]. The wire format is your choice; only the round trip matters.
  • encode([""]) must decode back to [""], a list holding one empty string, not [].
  • encode(["a#b", "#", ""]) must handle strings that contain your delimiter characters.

Constraints

  • 0 <= strs.length <= 200, each string up to 200 characters.
  • Strings may contain any ASCII character; assume no character 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 as soon as a string contains a comma. Every fixed separator has this problem, no matter which character you pick.
Hint 2 Two approaches: escape the separator inside the data so it is unambiguous, or remove the need to search for a separator by stating up front how many characters to read.
Hint 3 Prefix each string with its length and 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug