Arrays and Hashing Hash map lookups

64. Encode and Decode Strings

Medium

You are given a list of strings words. Write two functions. encode packs the whole list into one string. decode takes that string and returns the original list, with every word exactly as it was and in the same order.

A word can hold any printable ASCII character, including spaces, commas, digits and #. A word can also be empty, and so can the list.

decode must rebuild the list from the packed string alone. It cannot use anything encode saved, such as a field on the class.

Example 1

Input: words = ["pack", "my", "bag"]

Output: ["pack","my","bag"]

Explanation: Any packed string works, as long as decode can read the list back out of it.

Example 2

Input: words = ["a,b", "", "#1 two"]

Output: ["a,b","","#1 two"]

Explanation: The first word holds a comma, the second is empty, and the third starts with #. All three come back exactly as they were.

Example 3

Input: words = []

Output: []

Explanation: An empty list must come back empty. That is not the same as a list holding one empty word, which must come back as [""].

Check your understanding

Work out the answer for this input before you write any code.

words = ["3#ab", "c"]

Constraints

  • 0 ≤ words.length ≤ 104
  • 0 ≤ words[i].length ≤ 200
  • All the words together hold at most 2 × 105 characters.
  • Every character is printable ASCII, codes 32 to 126.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.