Data Structures & Algorithms Hash Maps & Sets
💡
Exercise 34

Encode & Decode Strings 20 XP Medium

Ctrl+Enter Run Ctrl+S Save

Design an algorithm to encode a list of strings to a single string, and decode that single string back to the original list of strings.

The trick: prefix each string with its length followed by a delimiter. For example:

['hello', 'world'] → '5#hello5#world' # 5# means next 5 chars are 'hello' # 5# means next 5 chars are 'world'

This way, even if strings contain our delimiter character, we can still correctly decode by reading the exact number of characters specified by the length.

📋 Instructions
Implement `encode(strs)` and `decode(s)` functions. Encode `['hello', 'world']`, then decode it back and print the result. Expected output: `['hello', 'world']`
Encode: for each string, prepend len(s) + '#' + s. Decode: read digits until '#', get the length n, then read next n characters as the string.
🧪 Test Cases
Input
decode(encoded)
Expected
['hello', 'world']
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.