Encode and Decode Strings solution explained

The Encode and Decode Strings solution writes each string as its length, a separator character and then the string itself, such as 5#hello. The decoder reads digits up to the first separator, then takes exactly that many characters, so the strings may contain any character, the separator included. Both directions run in O(total length) time, and an empty list and a list holding one empty string encode differently.

By Published 7 min read

The problem in plain words

Two programs need to pass a list of strings through a channel that only carries a single string. Write the function that packs the list into one string and the function that unpacks it again. The strings can contain anything: spaces, punctuation, digits, line breaks, non-English characters, and whatever character you might think of using as a separator. The decoded list must match the original exactly, including empty strings and the order of items.

Examples produced by the length-prefix code on this page
ListEncodedNote
["hi", "", "a#b"]2#hi0#3#a#bThe # inside a#b is harmless because the decoder already knows to take 3 characters
[""]0#One empty string
[](empty string)No strings at all; must differ from the line above
["12#", "#12"]3#12#3##12Digits and separators inside the data
Examples produced by the length-prefix code on this page. Scroll sideways on a small screen.

Why interviewers like it

It is a small design question disguised as a string problem. The obvious first idea, joining with a comma or some unusual character, is wrong, and the interviewer wants to see whether you find the counterexample yourself. It then opens a discussion about trade-offs that real systems face: escaping versus length prefixes, text versus binary lengths, and what happens with characters that take more than one unit of storage.

Follow-up questions

  • Can you do it without the separator character? Use a fixed-width length, such as four bytes or eight hex digits, in front of each string.
  • Make it robust to corrupted input. Validate that each length field is all digits and that enough characters remain.
  • Stream it. Length prefixes let a reader process one string at a time without holding the whole message.
  • Non-ASCII text. Lengths must be counted in the same units on both sides. Python counts code points; JavaScript counts UTF-16 units, so an emoji has length 1 in Python and 2 in JavaScript. Each language round-trips its own output correctly, but mixing them needs an agreed unit such as UTF-8 bytes.
  • Why not use JSON? In real code you often would. In the interview, the point is to show you can build the framing yourself.

The trap: joining with a delimiter

Joining with a comma and splitting on commas looks fine until one string contains a comma. Choosing an exotic character only makes the failure rarer, not impossible, because the problem allows any character. There is a second, quieter bug: with a plain join, an empty list and a list containing one empty string both become the empty string, so they cannot be told apart. Say both problems out loud; finding them is part of the answer.

A correct first answer: escaping

Escaping keeps the delimiter idea but makes it safe. Pick an escape character, here a slash. Double every slash that appears in the data, and end each item with a slash followed by a colon. When decoding, a slash is always followed by either another slash (a real slash in the data) or a colon (the end of an item), so there is no ambiguity. It is correct for any input, but decoding must inspect every character and the encoded string can grow when the data contains many slashes.

def encode_escaped(strings):
    # "/" becomes "//", and "/:" marks the end of each item
    return "".join(s.replace("/", "//") + "/:" for s in strings)

def decode_escaped(blob):
    items, current, i = [], [], 0
    while i < len(blob):
        if blob[i] == "/":
            if blob[i + 1] == ":":
                items.append("".join(current))
                current = []
            else:
                current.append("/")
            i += 2
        else:
            current.append(blob[i])
            i += 1
    return items
Escaping: "/" becomes "//" and "/:" ends an item. O(total length) both ways.

The expected answer: length prefixes

Write each string's length in decimal, then a "#", then the string. The decoder starts at position i, finds the next "#", and reads the digits before it as the length. That "#" must be the separator, because the length field contains only digits. The decoder then takes exactly that many characters as the string and continues right after them. Because it never looks inside the string for a separator, the string may contain "#", digits or anything else. An empty list encodes to an empty string, while [""] encodes to "0#", so the two cases stay distinct.

def encode(strings):
    return "".join(f"{len(s)}#{s}" for s in strings)

def decode(blob):
    items, i = [], 0
    while i < len(blob):
        j = blob.index("#", i)  # the first "#" after a length is always the separator
        size = int(blob[i:j])
        items.append(blob[j + 1 : j + 1 + size])
        i = j + 1 + size
    return items
Python: length, "#", string. O(total length) to encode and decode.
function encode(strings) {
  return strings.map((s) => `${s.length}#${s}`).join("");
}

function decode(blob) {
  const items = [];
  let i = 0;
  while (i < blob.length) {
    const j = blob.indexOf("#", i);
    const size = Number(blob.slice(i, j));
    items.push(blob.slice(j + 1, j + 1 + size));
    i = j + 1 + size;
  }
  return items;
}
JavaScript: the same format; lengths are counted in UTF-16 units.

One subtle point: in the decoder, the search for "#" starts at the beginning of a length field, never inside a string's content, because the previous step jumped exactly past the previous string. That is why a "#" inside the data cannot be mistaken for a separator.

Cost of each approach

For k strings with total length L
ApproachEncodeDecodeNotes
Join and split on a delimiterO(L + k)O(L + k)Incorrect when data contains the delimiter; [] and [""] collide
EscapingO(L + k)O(L + k), every character inspectedCorrect; output grows with escaped characters
Length prefix with a separatorO(L + k log L)O(L + k log L)Correct; prefixes add a few digits per string
Fixed-width lengthO(L + k)O(L + k)No separator needed; wastes space on short strings
For k strings with total length L. Scroll sideways on a small screen.

The log L term is just the number of digits in each length, which is tiny in practice; most people call both directions O(L).

Inputs to test

  • An empty list and a list with one empty string; they must encode differently and decode back to themselves.
  • Strings made only of the separator, such as "#" or "##".
  • Strings that start with digits followed by the separator, such as "12#".
  • Strings with ten or more characters, so the length has more than one digit.
  • Non-ASCII text, including an emoji, to confirm the lengths and slices use the same units.

Common slips

  • Splitting the encoded string on "#", which reintroduces the delimiter bug.
  • Assuming lengths are single digits and reading only one character for the length.
  • Measuring length in bytes on one side and in characters on the other.
  • Returning [""] for an empty input string, or [] for "0#".
  • Forgetting to move the index past the string after reading it, which loops forever.

How to explain it out loud

Fictional example

Finding the counterexample, then fixing it
Candidate
My first thought is to join with a comma, but a string could contain a comma, and the problem allows any character, so any single delimiter can break.
Candidate
Instead I'll write each string's length, a hash sign, then the string. The decoder reads digits up to the hash, then takes exactly that many characters. It never searches inside the string, so hashes in the data are fine.
Candidate
That also keeps an empty list and a list with one empty string apart: nothing versus zero-hash. Both directions are linear in the total length.

Reverse Integer is another place where careful number handling makes or breaks the answer. Valid Sudoku is a different kind of careful bookkeeping over a fixed structure. For a design question that also needs two pieces working together, see LRU Cache, and for matching structure in text, Valid Parentheses.

Practicing with Natively

The hard part of this problem is spotting what breaks the simple answer. When you practice on a Mac or Windows PC, Natively can read the prompt from a screenshot, give you a string that defeats your delimiter, and talk through escaping versus length prefixes. Its transcript of a mock interview lets you check whether you named the [] versus [""] case before the interviewer had to.

Questions people ask

How do you encode a list of strings into one string?

Write each string as its length, a separator such as "#", and then the string. To decode, read the digits up to the separator, then take exactly that many characters, and repeat.

Why not join the strings with a delimiter?

Any string might contain the delimiter, which splits it in the wrong place, and an empty list and a list with one empty string both become the empty string. Length prefixes avoid both problems.

Can the strings contain the # character?

Yes. The decoder only looks for "#" at the start of a length field, which contains digits only, and then skips over the string's content without inspecting it.

What is the time complexity of Encode and Decode Strings?

Linear in the total length of all strings for both encode and decode, plus a few digits of length prefix per string.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP