Encode and Decode Strings

MediumHash Maps and Sets

You want to send a list of strings over a channel that can carry only one string. Design two functions:

  • encode(strs) turns the list into a single string.
  • decode(s) takes that string and returns the original list, with the same strings in the same order.

The strings can contain any characters: commas, digits, #, spaces, newlines, even text that looks like your own encoding. Some strings may be empty, and the list itself may be empty. decode receives nothing except the string encode produced, so you cannot use shared state between the two calls.

The tests call a function roundTrip(strs). Write encode and decode in your file (in JavaScript the starter already has them as stubs), and have roundTrip return the pair [encode(strs), decode(encode(strs))]. A test passes when the first item is a string and the second item equals the input list exactly. (In Python, define encode, decode and round_trip yourself.)

Constraints

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • Strings may contain any characters, including the ones you choose as separators.

Examples

Example 1

Input: strs = ["lint","code","love","you"]
Output: ["(any single string)",["lint","code","love","you"]]

Four ordinary words. After encode then decode you must get exactly the same four words, in the same order.

Example 2

Input: strs = ["we","say",":","yes"]
Output: ["(any single string)",["we","say",":","yes"]]

A string that is just a punctuation mark is still data: it must survive unchanged.

Example 3

Input: strs = []
Output: ["(any single string)",[]]

An empty list encodes to a string (possibly empty) that decodes back to an empty list, not to a list holding one empty string.

JavaScript you'll use: Strings and characters Arrays: create, read, update

/** @param {string[]} strs @return {string} one string that decode can turn back into strs */
function encode(strs) {
  
}

/** @param {string} s @return {string[]} the original list */
function decode(s) {
  
}

// The tests call this one. Keep it as is.
function roundTrip(strs) {
  const encoded = encode(strs);
  return [encoded, decode(encoded)];
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.