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

Published: 20 June 2026
on channel: 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


On this page of the site you can watch the video online Encode and Decode Strings, Explained — Pack a List Into One String (LeetCode 271) with a duration of hours minute second in good quality, which was uploaded by the user Unrote 20 June 2026, share the link with friends and acquaintances, this video has already been watched 24 times on youtube and it was liked by 0 viewers. Enjoy your viewing!