Tutorialspoint
Problem
Solution
Submissions

Encode and Decode Strings

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to design an algorithm to encode a list of strings to a single string, and decode the single string back to the original list of strings. The encoding and decoding schemes should be stateless and must support all possible strings.

Example 1
  • Input: ["Hello", "World"]
  • Output: After encoding and then decoding, the result should be ["Hello", "World"]
  • Explanation:
    • The encoded string could be something like "5#Hello5#World" where "5#" represents the length of the string followed by a delimiter.
Example 2
  • Input: ["", "Learning", "is#fun"]
  • Output: After encoding and then decoding, the result should be ["", "Learning", "is#fun"]
  • Explanation:
    • The encoded string could be something like "0#8#Learning6#is#fun". Note how it handles empty strings and strings with delimiters.
Constraints
  • The number of strings in the list is between 0 and 10^4
  • The length of each string is between 0 and 200
  • The strings may contain any possible characters, including special characters
  • Time Complexity: O(n) where n is the total length of all strings
  • Space Complexity: O(n) for both encoding and decoding
StringseBayTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a length-based encoding scheme.
  • For each string, prepend its length followed by a delimiter before the actual string.
  • During decoding, read the length first, then the delimiter, and finally the string content.
  • Be careful with strings that might contain your delimiter character.
  • Make sure your encoding is unambiguous and can be correctly decoded.

Steps to solve by this approach:

 Step 1: For encoding, iterate through each string in the input list.
 Step 2: For each string, append its length, followed by a delimiter (such as '#'), followed by the actual string.
 Step 3: Combine all encoded strings into a single string.
 Step 4: For decoding, iterate through the encoded string.
 Step 5: Parse the length until we encounter the delimiter, then read that many characters to get the original string.
 Step 6: Repeat the process until we've decoded all strings.
 Step 7: Return the list of decoded strings.

Submitted Code :