Skip to main content
06

Encode and Decode Strings

Mediumstringsdesign

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Arrays & HashingRead the beginner guide

Design a way to send a list of strings over a channel that can only carry a single string.

Implement two functions:

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

Understand the problem

Think of it like packing for a move: encode packs several items into one box, and decode unpacks the box and must get back exactly the same items, in the same order. Nothing merged, nothing split, nothing lost.

You get to choose the packing format. The hard part is that the strings can contain any character, so whatever separator you pick might also appear inside a string.

text
Input:  ["neet", "code", "love", "you"]
encode → some single string (your choice of format)
decode → ["neet", "code", "love", "you"]

Your format must survive tricky inputs like these:

InputWhy it's tricky
[]An empty list must come back as an empty list.
[""]One empty string is different from no strings at all.
["", ""]Two empty strings, not one and not zero.
["a,b", "c"]If you separate with , this looks like 3 strings.
["4#x"]Contains digits and symbols you might use as markers.

Constraints

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] may contain any character.
  • Don't use a serialization library (JSON.stringify, json.dumps, pickle...).

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Before each string, write its length and a #, so the decoder always knows exactly how many characters to read next.

    The naive approach (and why it breaks)

    Here the naive approach isn't slow, it's wrong. Joining with a separator:

    text
    ["a", "b"]  → "a,b"
    ["a,b"]     → "a,b"   ← the same output for a different input!

    The decoder can't know which one you meant. Picking a rarer separator ("|", "🦄") only makes the bug rarer. The strings may contain any character, so any separator can appear inside one. You could add escaping (like \, in CSV files), but that gets complicated fast.

    The key insight

    The problem with a separator is that the decoder has to look at every character to find the end. Instead, tell it the length up front. Then it never needs to inspect the string's contents, so nothing inside a string can confuse it.

    This is called length-prefixing: each string becomes <length>#<string>.

    text
    ["neet", "", "4#x"]  →  "4#neet" + "0#" + "3#4#x"  →  "4#neet0#3#4#x"

    The # right after the length marks where the number ends (numbers can have several digits, like 12).

    Step by step

    Decoding "4#neet0#3#4#x", with i as our reading position:

    i beforeRead digits up to #LengthTake that many charactersi afterResult so far
    044neet6["neet"]
    600(empty string)8["neet", ""]
    8334#x13["neet", "", "4#x"]

    i reached the end of the string (13 characters), so we stop.

    Look at the last row: the string 4#x contains a # and a digit, but we never look for markers inside it. We just take 3 characters. That's why this format is safe for any input.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With m as the total number of characters across all strings:

    • Time: O(m) for both functions. Each character is written once and read once.
    • Memory: O(m) for the output.

    Common mistakes

    • Searching for # from the start of the whole string instead of from the current position i. You'd find a # from an earlier string.
    • Assuming lengths are one digit. A 12-character string writes 12#..., so read digits all the way up to the #.
    • Forgetting empty strings. 0# must produce "", not be skipped.

    Going deeper

    This is how real systems do it. HTTP sends a Content-Length header before a body, and many binary formats (like Protocol Buffers) write a size before each field instead of scanning for a terminator. Mentioning this in an interview shows you know the pattern is real, not just a puzzle trick.

    Reference solution

    js
    /**
     * @param {string[]} strs
     * @return {string}
     */
    export function encode(strs) {
      // Each string becomes "<length>#<string>", e.g. "neet" -> "4#neet".
      return strs.map((str) => `${str.length}#${str}`).join('')
    }
    
    /**
     * @param {string} s
     * @return {string[]}
     */
    export function decode(s) {
      const result = []
      let i = 0 // where the next "<length>#" starts
      while (i < s.length) {
        // The length is every digit from i up to the next '#'.
        // Search from i, not from 0, or we'd find a '#' from an earlier string.
        const hash = s.indexOf('#', i)
        const length = Number(s.slice(i, hash))
        // Take exactly `length` characters after the '#', whatever they are.
        result.push(s.slice(hash + 1, hash + 1 + length))
        // Jump past this string to the start of the next length.
        i = hash + 1 + length
      }
      return result
    }
    ts
    export function encode(strs: string[]): string {
      // Each string becomes "<length>#<string>", e.g. "neet" -> "4#neet".
      return strs.map((str) => `${str.length}#${str}`).join('')
    }
    
    export function decode(s: string): string[] {
      const result: string[] = []
      let i = 0 // where the next "<length>#" starts
      while (i < s.length) {
        // The length is every digit from i up to the next '#'.
        // Search from i, not from 0, or we'd find a '#' from an earlier string.
        const hash = s.indexOf('#', i)
        const length = Number(s.slice(i, hash))
        // Take exactly `length` characters after the '#', whatever they are.
        result.push(s.slice(hash + 1, hash + 1 + length))
        // Jump past this string to the start of the next length.
        i = hash + 1 + length
      }
      return result
    }
    python
    def encode(strs: list[str]) -> str:
        # Each string becomes "<length>#<string>", e.g. "neet" -> "4#neet".
        return "".join(f"{len(s)}#{s}" for s in strs)
    
    
    def decode(s: str) -> list[str]:
        result = []
        i = 0  # where the next "<length>#" starts
        while i < len(s):
            # The length is every digit from i up to the next '#'.
            # Search from i, not from 0, or we'd find a '#' from an earlier string.
            hash_index = s.index("#", i)
            length = int(s[i:hash_index])
            # Take exactly `length` characters after the '#', whatever they are.
            start = hash_index + 1
            result.append(s[start : start + length])
            # Jump past this string to the start of the next length.
            i = start + length
        return result