Encode and Decode Strings
Encode and Decode Strings Implement two functions: - encode(strs): List[str] -> str - decode(s): str -> List[str] Correctness requirement: decode(encode(strs)) must equal strs. Part 1 constraints: - Each input string contains only lowercase letters (a-z). - Strings may be empty. Example: encode(["hello", "world"]) → some encoded string decode(that string) → ["hello", "world"]
Implement encode, which turns a list of strings into one string, and decode, which turns that string back into the list. decode(encode(strs)) must return exactly strs, in the same order, including any empty strings. In Part 1 every string contains only English letters. Part 2 allows any characters, including digits and anything you might want to use as a separator. Part 3 adds characters such as '|' and backslash that break naive escaping.
Examples
You write
encode(strs: List[str])
decode(s: str)
Example 1
- Input
- ["hello", "world"]
- returns
- ["hello","world"]
Example 2
- Input
- ["Hello", "World"]
- returns
- ["Hello","World"]
The pattern behind it
Design
I reach for it when
- The statement describes a class with methods, not one function.
- Each method needs to be fast, and the structure decides how fast.
Say this before you type. Say each method, the cost you want from it, and the structure that earns that cost.
All 27 Design problemsStrings
I reach for it when
- The input is text and the answer is a count, a substring or a new string.
- You need to compare, reverse or rebuild characters.
Say this before you type. Say which array pattern the string is hiding before you touch a character.
All 51 Strings problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.
Each locked part opens in the editor once the part before it passes.