Encode and Decode Strings, Explained — Pack a List Into One String (LeetCode 271)

Publié le: 20 juin 2026
sur la chaîne: Unrote
24
0

Try it yourself — the full written explainer and an interactive visualizer are here:
https://unrote.com/problems/encode-an...

Encode and Decode Strings is one of those problems that looks trivial until you try it. Squeeze a whole list of strings into a single string, then recover the exact same list — and it has to survive strings that contain absolutely any character. The obvious answer, joining with a separator, quietly breaks the moment your data contains that separator. This video builds the bulletproof solution from zero: length-prefixing.

We work through a deliberately nasty example, ["cat", "n#5", "dog"], where the middle string contains the very character a naive approach would choke on. You will see exactly why splitting on a delimiter fails, why no delimiter is ever safe on arbitrary data, and how announcing each string's length up front ("3#cat") sidesteps the problem completely. The trick is counting instead of searching.

What we cover:
Why a separator collides with the data, every time
The length-prefix format: write the count, a hash, then the string
Encoding the list into one string, step by step
Decoding with a single pointer: read the length, count out the characters, jump ahead
Why it can never be ambiguous
The honest complexity: O(n) to encode, O(n) to decode, O(n) space
The reusable code shape
Where this shows up in the real world: HTTP Content-Length, Redis, netstrings, Protobuf

Chapters:
0:00 Intro
0:28 The problem
1:16 The obvious way (and why it breaks)
2:31 The fix: length-prefix
2:55 Encode walkthrough
3:58 Decode walkthrough
4:33 Complexity
4:56 The code shape
5:20 Where you see it
5:45 Recap

This is part of Unrote, where we learn data structures and algorithms by understanding them, not memorizing them. Patterns, not problems.

unrote.com
LeetCode 271 - Encode and Decode Strings


Sur cette page du site, vous pouvez voir la vidéo en ligne Encode and Decode Strings, Explained — Pack a List Into One String (LeetCode 271) durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Unrote 20 juin 2026, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 24 fois et il a aimé 0 téléspectateurs. Bon visionnage!