Encode and Decode Strings
Last Updated :
11 Dec, 2025
We are given an array of strings s[], and our task is to design an encoding–decoding system that allows this data to be safely transmitted over a network. We must implement an algorithm in the encode() function that converts the given array of strings into a single encoded string. This encoded string is then passed to the decode() function, which reconstructs and returns the original array of strings.
We need to implement the following two functions:
encode(): Takes an array of strings s[] and converts it into a single encoded string.decode(): Takes the encoded string as input and returns the original array of strings.
It is important that the encoding technique guarantees correct and lossless recovery of all strings. Also, we are not allowed to use any inbuilt serialization methods.
Examples:
Input: s = ["Hello", "World"]
Output: ["Hello", "World"]
Explanation: The encode() function will have the s as input, it will be encoded by one machine. Then another machine will receive the encoded string as the input parameter and then will decode it to its original form.
Input: s = ["abc","!@"]
Output: ["abc", "!@"]
Explanation: The encode() function will have the s as input, here there are two strings, one is "abc" and the other one has some special characters. It will be encoded by one machine. Then another machine will receive the encoded string as the input parameter and then will decode it to its original form.
[ Approach 1] Length-Based Encoding — O(n) Time and O(n) Space
The ides is, we avoid using any special delimiter and instead use the length of each string to guide the decoding process. In the encode() function, for every string, we store its length first, followed by a fixed separator (like #), and then the actual string content. This way, the encoded string becomes a continuous sequence of length–string pairs. During decoding, the decode() function reads the length first, then extracts exactly that many characters as the next string, and repeats this process until the entire encoded string is processed.
C++
#include <iostream>
#include<vector>
using namespace std;
// Encodes the array of strings into a single string
string encode(vector<string>& s) {
string encoded;
for (string &str : s) {
encoded += to_string(str.length()); // store length
encoded += '#'; // fixed separator
encoded += str; // actual string
}
return encoded;
}
// Decodes the encoded string back into the array of strings
vector<string> decode(string& s) {
vector<string> result;
int i = 0;
int n = s.length();
while (i < n) {
int len = 0;
// Extract the length
while (s[i] != '#') {
len = len * 10 + (s[i] - '0');
i++;
}
i++; // skip '#'
// Extract the actual string using the length
string temp = s.substr(i, len);
result.push_back(temp);
i += len;
}
return result;
}
int main() {
vector<string> s = {"Hello", "World"};
string encoded = encode(s);
vector<string> decoded = decode(encoded);
for (int i = 0; i < decoded.size(); i++) {
cout << decoded[i];
if (i + 1 < decoded.size()) cout << " ";
}
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
// Encode array of strings into a single string
static String encode(String[] arr) {
StringBuilder encoded = new StringBuilder();
for (String str : arr) {
encoded.append(str.length()); // store length
encoded.append('#'); // separator
encoded.append(str); // actual string
}
return encoded.toString();
}
// Decode encoded string back into array of strings
static String[] decode(String s) {
ArrayList<String> result = new ArrayList<>();
int i = 0;
int n = s.length();
while (i < n) {
int len = 0;
// Read length
while (s.charAt(i) != '#') {
len = len * 10 + (s.charAt(i) - '0');
i++;
}
i++; // skip '#'
// Read actual string
String temp = s.substring(i, i + len);
result.add(temp);
i += len;
}
// Convert List → Array
return result.toArray(new String[result.size()]);
}
public static void main(String[] args) {
String[] arr = {"Hello", "World"};
String encoded = encode(arr);
String[] decoded = decode(encoded);
for (int i = 0; i < decoded.length; i++) {
System.out.print(decoded[i]);
if (i + 1 < decoded.length) System.out.print(" ");
}
}
}
Python
# Encodes the array of strings into a single string
def encode(s):
encoded = ""
for str_val in s:
encoded += str(len(str_val)) # store length
encoded += '#' # fixed separator
encoded += str_val # actual string
return encoded
# Decodes the encoded string back into the array of strings
def decode(s):
result = []
i = 0
n = len(s)
while i < n:
length = 0
# Extract the length
while s[i] != '#':
length = length * 10 + (ord(s[i]) - ord('0'))
i += 1
i += 1 # skip '#'
# Extract the actual string using the length
temp = s[i:i + length]
result.append(temp)
i += length
return result
if __name__ == "__main__":
s = ["Hello", "World"]
encoded = encode(s)
decoded = decode(encoded)
for i in range(len(decoded)):
print(decoded[i], end=" ")
C#
using System;
using System.Collections.Generic;
class GFG
{
// Encodes the list of strings into a single string
static string encode(List<string> s)
{
string encoded = "";
// For each string, store: length + '#' + actual string
foreach (string str in s)
{
encoded += str.Length; // store length of the string
encoded += '#'; // fixed separator
encoded += str; // actual string content
}
return encoded;
}
// Decodes the encoded string back into list of strings
static List<string> decode(string s)
{
List<string> result = new List<string>();
int i = 0;
int n = s.Length;
while (i < n)
{
int len = 0;
// Read the length before '#'
while (s[i] != '#')
{
len = len * 10 + (s[i] - '0');
i++;
}
i++; // skip the '#'
// Extract the actual string using the length
string temp = s.Substring(i, len);
result.Add(temp);
i += len; // move to the next encoded part
}
return result;
}
static void Main()
{
List<string> s = new List<string> { "Hello", "World" };
string encoded = encode(s);
List<string> decoded = decode(encoded);
for (int i = 0; i < decoded.Count; i++)
{
Console.Write(decoded[i]);
if (i + 1 < decoded.Count) Console.Write(" ");
}
}
}
JavaScript
function encode(s) {
let encoded = "";
// For each string, append: length + '#' + actual string
for (let str of s) {
encoded += str.length; // store length of the string
encoded += '#'; // fixed separator
encoded += str; // actual string content
}
return encoded;
}
function decode(s) {
let result = [];
let i = 0;
while (i < s.length) {
let len = 0;
// Read the length before '#'
while (s[i] !== '#') {
len = len * 10 + (s.charCodeAt(i) - 48);
i++;
}
i++; // skip the '#'
// Extract the actual string using the length
let temp = s.substring(i, i + len);
result.push(temp);
i += len; // move to the next encoded part
}
return result;
}
//Driver Code
const s = ["Hello", "World"];
const encoded = encode(s);
const decoded = decode(encoded);
let output = "";
for (let i = 0; i < decoded.length; i++) {
output += decoded[i];
if (i + 1 < decoded.length) output += " ";
}
console.log(output);
[Approach 2] Escape-Based Delimiter Encoding — O(n) Time, O(n) Space
In this approach, instead of completely avoiding delimiters, we allow a delimiter character (such as #) to be used between strings but introduce an escape mechanism to handle cases where the delimiter itself appears inside the strings. Along with the delimiter, we also choose an escape character (such as \). During encoding, every occurrence of the escape character is first replaced with a double escape (\\), and every occurrence of the delimiter is replaced with an escaped version (\#). After this transformation, all strings are joined together using the delimiter. During decoding, the encoded string is scanned character by character, and the delimiter is treated as a split point only if it is not escaped. The escaped characters are then converted back to their original form.
C++
#include <iostream>
#include<vector>
using namespace std;
// Encodes the array of strings into a single string
string encode(vector<string>& s) {
string encoded;
char delim = '#';
char esc = '\\';
for (int k = 0; k < (int)s.size(); k++) {
string &str = s[k];
// Escape '\' as '\\' and '#' as '\#'
for (char c : str) {
if (c == esc || c == delim) {
encoded.push_back(esc);
}
encoded.push_back(c);
}
// Add delimiter between encoded strings (but not after last)
if (k != (int)s.size() - 1) {
encoded.push_back(delim);
}
}
return encoded;
}
// Decodes the encoded string back into the array of strings
vector<string> decode(string& s) {
vector<string> result;
string current;
char delim = '#';
char esc = '\\';
int n = s.length();
int i = 0;
while (i < n) {
if (s[i] == esc) {
// Next character is taken literally (escaped character)
if (i + 1 < n) {
current.push_back(s[i + 1]);
i += 2;
} else {
// Edge case: stray escape at end (can be handled as needed)
i++;
}
} else if (s[i] == delim) {
// Delimiter: end of one string
result.push_back(current);
current.clear();
i++;
} else {
// Normal character
current.push_back(s[i]);
i++;
}
}
// Add the last collected string
result.push_back(current);
return result;
}
int main() {
vector<string> s = {"Hello", "World"};
string encoded = encode(s);
vector<string> decoded = decode(encoded);
for (int i = 0; i < (int)decoded.size(); i++) {
cout << decoded[i];
if (i + 1 < (int)decoded.size()) cout << " ";
}
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
// Encodes the array of strings into a single string
static String encode(String[] arr) {
StringBuilder encoded = new StringBuilder();
char delim = '#';
char esc = '\\';
for (int k = 0; k < arr.length; k++) {
String str = arr[k];
// Escape '\' as '\\' and '#' as '\#'
for (char c : str.toCharArray()) {
if (c == esc || c == delim) {
encoded.append(esc);
}
encoded.append(c);
}
// Add delimiter between encoded strings (not after last)
if (k != arr.length - 1) {
encoded.append(delim);
}
}
return encoded.toString();
}
// Decodes the encoded string back into an array of strings
static String[] decode(String s) {
ArrayList<String> result = new ArrayList<>();
StringBuilder current = new StringBuilder();
char delim = '#';
char esc = '\\';
int n = s.length();
int i = 0;
while (i < n) {
if (s.charAt(i) == esc) {
// Take next character literally
if (i + 1 < n) {
current.append(s.charAt(i + 1));
i += 2;
} else {
i++;
}
} else if (s.charAt(i) == delim) {
// End of one string
result.add(current.toString());
current.setLength(0);
i++;
} else {
current.append(s.charAt(i));
i++;
}
}
// Add last collected string
result.add(current.toString());
// Convert List -> Array
return result.toArray(new String[0]);
}
public static void main(String[] args) {
String[] arr = {"Hello", "World"};
String encoded = encode(arr);
String[] decoded = decode(encoded);
for (int i = 0; i < decoded.length; i++) {
System.out.print(decoded[i]);
if (i + 1 < decoded.length) System.out.print(" ");
}
}
}
Python
def encode(s):
encoded = ""
delim = '#' # delimiter between encoded strings
esc = '\\' # escape character
for k, str_val in enumerate(s):
# Escape '\' as '\\' and '#' as '\#'
for c in str_val:
if c == esc or c == delim:
encoded += esc # add escape before special character
encoded += c # add the actual character
# Add delimiter between encoded strings (not after last)
if k != len(s) - 1:
encoded += delim
return encoded
def decode(s):
result = []
current = []
delim = '#'
esc = '\\'
i = 0
n = len(s)
while i < n:
if s[i] == esc:
# Next character is taken as a literal character
if i + 1 < n:
current.append(s[i + 1])
i += 2
else:
i += 1
elif s[i] == delim:
# Delimiter found -> end of one decoded string
result.append("".join(current))
current = []
i += 1
else:
# Normal character, just add to current string
current.append(s[i])
i += 1
# Add the last collected string
result.append("".join(current))
return result
if __name__ == "__main__":
s = ["Hello", "World"]
encoded = encode(s)
decoded = decode(encoded)
for i in range(len(decoded)):
print(decoded[i], end=" " if i + 1 < len(decoded) else "")
C#
using System;
using System.Collections.Generic;
class GFG
{
// Encodes the array of strings into a single string
static string encode(List<string> s)
{
string encoded = "";
char delim = '#';
char esc = '\\';
for (int k = 0; k < s.Count; k++)
{
string str = s[k];
// Escape '\' as '\\' and '#' as '\#'
foreach (char c in str)
{
if (c == esc || c == delim)
{
encoded += esc;
}
encoded += c;
}
// Add delimiter between encoded strings (but not after last)
if (k != s.Count - 1)
{
encoded += delim;
}
}
return encoded;
}
// Decodes the encoded string back into the array of strings
static List<string> decode(string s)
{
List<string> result = new List<string>();
string current = "";
char delim = '#';
char esc = '\\';
int n = s.Length;
int i = 0;
while (i < n)
{
if (s[i] == esc)
{
// Next character is taken literally (escaped character)
if (i + 1 < n)
{
current += s[i + 1];
i += 2;
}
else
{
// Edge case: stray escape at end (can be handled as needed)
i++;
}
}
else if (s[i] == delim)
{
// Delimiter: end of one string
result.Add(current);
current = "";
i++;
}
else
{
// Normal character
current += s[i];
i++;
}
}
// Add the last collected string
result.Add(current);
return result;
}
static void Main()
{
List<string> s = new List<string> { "Hello", "World" };
string encoded = encode(s);
List<string> decoded = decode(encoded);
for (int i = 0; i < decoded.Count; i++)
{
Console.Write(decoded[i]);
if (i + 1 < decoded.Count) Console.Write(" ");
}
}
}
JavaScript
function encode(s) {
let encoded = "";
let delim = '#'; // delimiter between encoded strings
let esc = '\\'; // escape character
for (let k = 0; k < s.length; k++) {
let str = s[k];
// Escape '\' as '\\' and '#' as '\#'
for (let c of str) {
if (c === esc || c === delim) {
encoded += esc; // add escape before special character
}
encoded += c; // add actual character
}
// Add delimiter between encoded strings (not after last)
if (k !== s.length - 1) {
encoded += delim;
}
}
return encoded;
}
function decode(s) {
let result = [];
let current = [];
let delim = '#';
let esc = '\\';
let i = 0;
let n = s.length;
while (i < n) {
if (s[i] === esc) {
// Next character is taken literally
if (i + 1 < n) {
current.push(s[i + 1]);
i += 2;
} else {
i++;
}
} else if (s[i] === delim) {
// Delimiter found -> end of one decoded string
result.push(current.join(""));
current = [];
i++;
} else {
// Normal character, just add to current string
current.push(s[i]);
i++;
}
}
// Add the last collected string
result.push(current.join(""));
return result;
}
//Driver Code
const s = ["Hello", "World"];
const encoded = encode(s);
const decoded = decode(encoded);
let output = "";
for (let i = 0; i < decoded.length; i++) {
output += decoded[i];
if (i + 1 < decoded.length) output += " ";
}
console.log(output);
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem