# Encode and Decode Strings

- **Canonical ID**: `encode-and-decode-strings`
- **Canonical URL**: https://dsacheatsheet.com/problems/encode-and-decode-strings
- **Difficulty**: medium
- **Patterns**: Arrays & Hashing
- **Version**: 1.0.0 (verified 2026-11-11T21:00:00Z)
- **Original Problem**: https://leetcode.com/problems/encode-and-decode-strings/

## 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

- **Time Complexity**: `O(N)`
- **Space Complexity**: `O(N)`
- **Proof**: Linear framing reads length headers and slices payload chunks without backtracking or escaping overhead.

## 3. Minimal Idiomatic Code

### Python
```python
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
```

### TypeScript
```typescript
export class Codec {
  encode(strs: string[]): string {
    return strs.map((s) => `${s.length}#${s}`).join('');
  }
  decode(s: string): string[] {
    const res: string[] = [];
    let i = 0;
    while (i < s.length) {
      const j = s.indexOf('#', i);
      const len = parseInt(s.slice(i, j), 10);
      i = j + 1;
      res.push(s.slice(i, i + len));
      i += len;
    }
    return res;
  }
}
```

### C++
```cpp
class Codec {
public:
    string encode(vector<string>& strs) {
        string out;
        for (auto& s : strs) out += to_string(s.size()) + "#" + s;
        return out;
    }
    vector<string> decode(string s) {
        vector<string> res;
        size_t i = 0;
        while (i < s.size()) {
            size_t j = s.find('#', i);
            int len = stoi(s.substr(i, j - i));
            res.push_back(s.substr(j + 1, len));
            i = j + 1 + len;
        }
        return res;
    }
};
```

### Java
```java
public class Codec {
    public String encode(List<String> strs) {
        StringBuilder sb = new StringBuilder();
        for (String s : strs) sb.append(s.length()).append('#').append(s);
        return sb.toString();
    }
    public List<String> decode(String s) {
        List<String> res = new ArrayList<>();
        int i = 0;
        while (i < s.length()) {
            int j = s.indexOf('#', i);
            int len = Integer.parseInt(s.substring(i, j));
            res.add(s.substring(j + 1, j + 1 + len));
            i = j + 1 + len;
        }
        return res;
    }
}
```

### Go
```go
func Encode(strs []string) string {
    var b strings.Builder
    for _, s := range strs { fmt.Fprintf(&b, "%d#%s", len(s), s) }
    return b.String()
}
```

## 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.
