Encode and Decode Strings

mediumTests passed 2026-11-11v1.0.0

1. Core Invariant / The Trick

Length-prefix framing (`<len>#<string>`). Read digits up to `#` to know the exact payload character count `L`, then slice the next `L` characters literally—content characters like `#` inside payloads are never ambiguous.

2. Complexity Bounds & Proof

Linear framing reads length headers and slices payload chunks without backtracking or escaping overhead.

3. Minimal Idiomatic Code

class Codec:
    def encode(self, strs: list[str]) -> str:
        return "".join(f"{len(s)}#{s}" for s in strs)

    def decode(self, s: str) -> list[str]:
        res, i = [], 0
        while i < len(s):
            j = s.index('#', i)
            length = int(s[i:j])
            i = j + 1
            res.append(s[i:i + length])
            i += length
        return res

4. Failure Modes & Interview Follow-ups

Pitfalls:- Using delimiter escaping breaks when arbitrary UTF-8 or escape chars appear unescaped; length-prefix framing is universally safe.
Follow-ups:- Binary protocol framing (HTTP/2 frames, protobuf varints) uses the exact same length-prefix invariant.

Personal Notes & Scratchpad (Local-First Yjs CRDT)

Saved instantaneously in IndexedDB. Streams live across peers via Hocuspocus when signed in.

Browser Scratchpad
Console Output
Click Run or press Cmd/Ctrl+Enter to execute locally in a Web Worker.