13/36
Part 3 of 8 · Open and closeLearn and do

A length in front of each string needs no stack

A related problem has no stack at all. Encode and Decode Strings is on the compiled LeetCode list for OpenAI (1 source). A prep guide lists it for Anthropic (1 source). Pack a list of strings into one string, and get the same list back.

A separator breaks as soon as a string contains it. Put each string's length in front instead, and the decoder never has to guess:

def encode(strings):
    return "".join(f"{len(s)}:{s}" for s in strings)


packed = encode(["a:b", "", "3:x", "naïve"])
print(packed)
Predict

encode puts each string's length and a colon in front of it. What does encode(["a:b", "", "3:x", "naïve"]) give?

Pick one to see what it prints.
Pick an answer above to see the rest