Encode and Decode Strings

MediumArrays and hashing

Write two functions. encode(strs) turns a list of strings into one string, and decode(s) turns that string back into the original list.

Each test calls encode on a list, passes what it returns to decode, and expects the very same list back, in the same order. The strings can hold any character, including digits, #, commas and spaces; a string can be empty, and so can the list. decode must rebuild the list from the string alone; keep nothing between the two calls.

Examples

Example 1
Input:  strs = ["red", "green", "blue"]
Output: ["red", "green", "blue"]

The list is encoded into one string, and decoding it gives the three words back.

Example 2
Input:  strs = ["2#ab", "", "x,y"]
Output: ["2#ab", "", "x,y"]

Digits, # and commas can be part of a string, and a string can be empty.

Constraints

  • 0 ≤ strs.length ≤ 200
  • 0 ≤ strs[i].length ≤ 200
  • Strings can contain any of the 256 ASCII characters.

Stuck?

Hint 1

Any separator you choose can also appear inside a string, so a separator alone cannot tell you where one string ends.

Hint 2

Write each string’s length in front of it, followed by a marker: 5#hello. To decode, read the digits up to the marker, then take exactly that many characters, whatever they are.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur