DSA Tracker

Medium

Encode and Decode Strings

A medium Strings problem included in Love Babbar 450. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Strings
Sheets
1
Core for
13 roles
Platform
LeetCode

The problem

Design an encoding scheme that converts a list of strings into a single string and a decoding scheme that reconstructs the original list from the encoded string.

Example 1

Input
["Hello","World"]
Output
encoded then decoded back to ["Hello","World"]

Example 2

Input
[""]
Output
encoded then decoded back to [""]

Example 3

Input
["a","b","c"]
Output
encoded then decoded back to ["a","b","c"]

Constraints

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200

How to think about it

Updated 2026-09-09

Any delimiter choice can appear legitimately inside the payload strings. The only invariant that remains uncorrupted is the exact byte length of the upcoming token. Prefixing each item with its integer character count followed by an unambiguous separator turns the stream into a sequence of self-describing segments where content can contain any symbol.

Approaches, worst first

  1. Escaped delimiter

    time O(n) · space O(n)

    Join strings with a special character like comma or semicolon, escaping instances of that character in the payload with backslashes. Correct, but parsing requires a state machine inspecting character-by-character to handle escaped backslashes and edge cases.

  2. Length-prefixed framingWrite this one

    time O(n) · space O(n)

    Format each string as length + '#' + string. The decoder reads digits until hitting '#', parses the integer length k, extracts the next k characters unconditionally as one token, and immediately repeats for the next framing token.

Where people lose marks · 3
  • Empty string items inside a list like [''] must preserve their count 0 and recreate empty tokens, unlike an empty list [] which contains zero items.
  • Delimiter '#' appearing inside string content: the decoder must jump exactly k characters forward after parsing the length integer, rather than searching for the next '#' delimiter blindly.
  • Accumulating strings naively in an immutable language creates repeated intermediate allocations; use string slices or an array buffer.

Full solution

Length-prefixed framing: each item becomes length + '#' + content, so the decoder reads the count and jumps exactly that many characters — any symbol, including '#', can appear in the payload with no escaping.

Python
def encode(strs: list[str]) -> str:
    # length-prefixed framing: "<len>#<chars>" per item, so '#' inside content is safe
    return "".join(f"{len(s)}#{s}" for s in strs)


def decode(s: str) -> list[str]:
    out: list[str] = []
    i = 0
    while i < len(s):
        j = s.index("#", i)          # digits between i and j are the length
        k = int(s[i:j])
        out.append(s[j + 1:j + 1 + k])  # jump exactly k chars, never search for '#'
        i = j + 1 + k
    return out
JavaScript
function encode(strs) {
  // length-prefixed framing: "<len>#<chars>" per item, so '#' inside content is safe
  return strs.map((s) => `${s.length}#${s}`).join("");
}

function decode(s) {
  const out = [];
  let i = 0;
  while (i < s.length) {
    const j = s.indexOf("#", i); // digits between i and j are the length
    const k = Number(s.slice(i, j));
    out.push(s.slice(j + 1, j + 1 + k)); // jump exactly k chars, never search for '#'
    i = j + 1 + k;
  }
  return out;
}
Try it in the editor

The theory behind it

Strings — the ground this problem stands on. All Strings problems

What Strings is

A string is an ordered necklace of text characters, like letters printed along a ribbon of paper. Each character sits at an exact numeric slot, holding a glyph such as a letter, punctuation mark, or digit. In many programming languages, ribbons cannot be edited after creation, meaning changing a single character requires pressing an entirely new ribbon from scratch.

When to reach for it

Reach for string techniques when inputs consist of words, DNA sequences, serialized data formats, or sentences. Clues include questions testing palindromes, anagram matches, substring patterns, parenthesis balancing, or character frequency counts. Whenever an algorithm asks to transform capitalization, parse structured tokens, or compute edits between two phrases, string representations are the core subject.

How the pattern works

Think of characters as small integer codes ranging across standard character sets. Frequency tables with fixed sizes often replace heavy hash maps when tallying occurrences. For search tasks, maintain rolling state using character indices or sliding borders. When building output text through repeated appends, accumulate pieces inside a mutable list or string builder rather than concatenating strings directly, avoiding quadratic copy overhead.

What each operation costs

OperationTime
read character by indexO(1)
concatenate two strings of total length nO(n)
compare two strings of length nO(n)
What usually goes wrong with Strings
  • Concatenating strings inside a loop using the plus operator, which silently creates full copies on each iteration and turns linear routines into quadratic slowdowns.
  • Assuming all characters fall strictly within lowercase English letters without validating spaces, uppercase variants, punctuation marks, or multi-byte unicode symbols.
  • Confusing substring length with end index when slicing, causing unexpected off-by-one truncations in languages that take length versus exclusive end position.

Which roles need this problem

Strings is a core topic for these 13 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 7 more roles, including Data Engineer, Data Analyst, Embedded / Firmware Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Strings problems

Problem set and role mapping as of .