DSA AnimatorREVISION VIDEOS
← Back to problems
New

Encode and Decode Strings — LeetCode 271 video explanation

Design an encode function that turns a list of strings into one string. And a decode function that turns that string back into the exact same list. The strings can contain any character, including the one you might want to use as a separator.

Loading videos…

DSA Animator › DSA Revision › Strings › Encode and Decode Strings

Key moments in the Encode and Decode Strings video

0:04Problem0:19Example0:28Brute force0:37Key idea0:48Dry run1:07Code1:23Takeaway

What you will learn

Remember: length prefixes make any content safe. Read the length first, then read exactly that many characters. The video solves Encode and Decode Strings (LeetCode 271, Medium) with the Length Prefix pattern from the Strings topic, and you can replay every step in the interactive Encode and Decode Strings animation.

Encode and Decode Strings video transcript

Problem

Design an encode function that turns a list of strings into one string. And a decode function that turns that string back into the exact same list. The strings can contain any character, including the one you might want to use as a separator.

Example

For the list h i, and a hash b, the encoded string is 2 hash h i, 3 hash a hash b. Decoding it gives back h i, and a hash b.

Brute force

Joining with a separator, like a comma, breaks as soon as a word contains a comma. Escaping special characters works, but it is fiddly and easy to get wrong.

Key idea

Put the length of each word in front of it, followed by a hash. To decode, read digits up to the hash, which gives the length. Then take exactly that many characters, no matter what they are.

Dry run

Encode h i as 2, hash, h i. Encode a hash b as 3, hash, a hash b. Decoding starts at 0: the digits before the first hash say 2, so read h i. Next, the digits say 3, so read the next 3 characters, a hash b, even though one of them is a hash. The list comes back exactly as it was.

Code

In code, encode appends the length, a hash, and the word, for every word. Decode finds the next hash from the current index, and parses the length before it. It takes that many characters after the hash, and jumps past them. Both directions are O of total length in time and space.

Takeaway

Remember: length prefixes make any content safe. Read the length first, then read exactly that many characters.

More Strings revision videos

← All 185 DSA revision videos