loading

Encode and Decode Strings — Step-by-Step Visualization

mediumLeetCode #271ArrayStringDesign

Design an algorithm to encode a list of strings to a single string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Algorithm Pattern

Length Prefixed Encoding

Key Idea

To distinguish between the separator and the content of the strings, we prepend each string with its length follow by a special character (e.g., `#`). For example, `hello` becomes `5#hello`. During decoding, we read the length until we hit `#`, then read the guaranteed number of characters specified by that length.

Step-by-Step Approach

  1. Encode:
  2. For each string `s`, append `len(s) + '#' + s` to a result string.
  3. Decode:
  4. Use a pointer `i` to traverse the encoded string.
  5. Find the next `#` starting from `i` to get the length `n`.
  6. Extract the substring from `index of # + 1` with length `n`.
  7. Move `i` past the extracted substring and repeat.

Common Gotchas

  • The '#' character itself can be inside the string; the length prefix prevents ambiguity.
  • Empty strings should be handled (e.g., `0#`).

Related Problems