Encode and Decode Strings

Asked byFacebookLinkedIn

Problem

Design an algorithm to encode a list of strings into a single string, and a corresponding decode function that reconstructs the original list of strings from the encoded string. The encoding must correctly handle strings that contain any character, including whatever delimiter you choose to use.

Examples

Example 1
Input:strs = ["lint","code","love","you"]
Output:["lint","code","love","you"]
decode(encode(strs)) reproduces the original list.
Example 2
Input:strs = ["we","say",":","yes"]
Output:["we","say",":","yes"]

Constraints

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] may contain any valid ASCII character.

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Arrays & Hashing pattern

Arrays give O(1) index access; hash maps and sets give O(1) average lookup, insert, and delete by trading space for speed. Together they're the toolkit for turning brute-force O(n²) comparisons into a single O(n) pass.

Look for this pattern when

  • You need to check "have I seen this value before?" quickly.
  • You're counting occurrences or grouping items by a derived key (e.g. sorted letters for anagrams).
  • A nested loop is comparing every pair — a hash map can often replace the inner loop.

Read the full Arrays & Hashing guide →

Video walkthroughs

Original problem on LeetCode ↗

More Arrays & Hashing problems