Skip to content

Encode and Decode Strings

Medium Day 12 • Striver Blind 75

Design an algorithm to encode a list of strings to a single string, and decode it back.

Example 1:

  • Input: strs = ["leet","code","love","you"]
  • Output: ["leet","code","love","you"]

Constraints:

  • 0 <= strs.length <= 200

Prefix each string with length and a delimiter (e.g., 4#leet4#code).

Length Prefix Framing


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
Start["Input Data"] --> Process["Process Element by Element"]
Process --> Lookup{"Hash Map / Set Lookup"}
Lookup -- "Match Found" --> Return["Return Indices / Result"]
Lookup -- "No Match" --> Store["Store in Map / Set"]
Store --> Process

function encode(strs) {
return strs.map(s => s.length + '#' + s).join('');
}
function decode(s) {
const res = [];
let i = 0;
while (i < s.length) {
let j = s.indexOf('#', i);
let len = parseInt(s.substring(i, j));
res.push(s.substring(j + 1, j + 1 + len));
i = j + 1 + len;
}
return res;
}
function encodeDecode(strs) {
return decode(encode(strs));
}
  • Time Complexity: O(N)
  • Space Complexity: O(N)
  • Explanation: Length-delimited framing.

function encode(strs) {
return strs.map(s => s.length + '#' + s).join('');
}
function decode(s) {
const res = [];
let i = 0;
while (i < s.length) {
let j = s.indexOf('#', i);
let len = parseInt(s.substring(i, j));
res.push(s.substring(j + 1, j + 1 + len));
i = j + 1 + len;
}
return res;
}
function encodeDecode(strs) {
return decode(encode(strs));
}
  • Time Complexity: O(N)
  • Space Complexity: O(N)
  • Explanation: Chunk length prefix encoding.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Prefixing length before delimiter makes parsing unambiguous regardless of internal string characters.


  1. Format each string as length + ’#’ + string.

👉 Solve this problem interactively in the DSA Lab