← Back to Codes

2026-06-09 16:36:42

Encode and Decode Strings in Python and Java | LeetCode #271

Learn how to solve Encode and Decode Strings in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Encode and Decode Strings in Python and Java

In this tutorial, we will learn LeetCode #271: Encode and Decode Strings in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Encode and Decode Strings Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use length prefix encoding because it gives a clean and optimized solution.

Example input:
strs = ["tree", "4#code", ""]

Expected result:
Output: decoded original list

Explanation:
Length prefix avoids confusion.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
strs = ["tree", "4#code", ""]

Approach:
length prefix encoding

We update variables step by step until we reach:
Output: decoded original list

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why length prefix encoding is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

strs = ["tree", "4#code", ""]

We will solve it using length prefix encoding.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: decoded original list

Why?
Length prefix avoids confusion.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: decoded original list

Example 1

Input:
strs = ["tree", "4#code", ""]

Output:
Output: decoded original list

Explanation:
Length prefix avoids confusion.

Example 2

Input:
strs = ["hello", "world", "!"]

Output:
decoded list is the same

Explanation:
Length prefixes allow each string to be restored exactly.

Python Code

Here is the complete Python solution for LeetCode #271.

class StringCodec:
    def encode(self, strings):
        result = []
        for text in strings:
            result.append(str(len(text)) + "#" + text)
        return "".join(result)

    def decode(self, encoded):
        result = []
        index = 0

        while index < len(encoded):
            delimiter = encoded.index("#", index)
            length = int(encoded[index:delimiter])
            start = delimiter + 1
            result.append(encoded[start:start + length])
            index = start + length

        return result


codec = StringCodec()
encoded = codec.encode(["code", "java", "py#thon"])
print(encoded)                # Output: 4#code4#java7#py#thon
print(codec.decode(encoded))  # Output: ['code', 'java', 'py#thon']

Java Code

Here is the complete Java solution for LeetCode #271.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class StringCodec {
    public String encode(List<String> strings) {
        StringBuilder result = new StringBuilder();
        for (String text : strings) {
            result.append(text.length()).append('#').append(text);
        }
        return result.toString();
    }

    public List<String> decode(String encoded) {
        List<String> result = new ArrayList<>();
        int index = 0;

        while (index < encoded.length()) {
            int delimiter = encoded.indexOf('#', index);
            int length = Integer.parseInt(encoded.substring(index, delimiter));
            int start = delimiter + 1;
            result.add(encoded.substring(start, start + length));
            index = start + length;
        }

        return result;
    }

    public static void main(String[] args) {
        StringCodec codec = new StringCodec();
        String encoded = codec.encode(Arrays.asList("code", "java", "py#thon"));
        System.out.println(encoded);              // 4#code4#java7#py#thon
        System.out.println(codec.decode(encoded)); // [code, java, py#thon]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #271: Encode and Decode Strings becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.