v9.1.1
Menu

Encode and Decode Strings

mediumPROHash Maps & CountingDSA for AI Engineers

Design an algorithm to encode a list of strings into a single string and decode it back.

Implement encode(strs), which takes a list of strings and returns one string, and decode(s), which takes that string and returns the original list. For every valid input, decode(encode(strs)) must equal strs exactly (same order, same count, empty strings preserved).

Input: a list of strings (the example shows it comma-separated for display only). Output: the decoded strings, one per line.

Example

Input
hello,world
Output
hello
world
Reasoning
  • Input: a list of n=2n = 2 strings, hello and world (shown comma-separated only for display), each 5 characters long. encode must turn the whole list into one string; decode must turn that string back into exactly the original list.
  • The requirement: decoding must undo encoding, decode(encode(L))=L\text{decode}(\text{encode}(L)) = L for every list LL, including the empty list, empty strings, and strings that contain commas or any other character.
  • Why plain joining fails: the lists [hello, world], [hellow, orld] and [helloworld] all glue into the same 10 characters. If two different lists produce the same encoded string, no decoder can tell which one it came from, so the encoding must record where each string ends without relying on any character being absent from the data.
  • Output: the recovered list has 2 entries, printed one per line: hello then world.
  • Notice that a comma delimiter would break on a list holding the string "a,b" and an empty string: it must come back as 2 strings, not 3.

Constraints

  • 0 <= len(strs) <= 200
  • 0 <= len(strs[i]) <= 200
  • strs[i] may contain any character including commas

More from DSA for AI Engineers

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.