↻one more pass.
Strings · Medium

Encode and Decode Strings: the idea to remember.

Encode a list of arbitrary strings into one string and recover the exact list, including empty strings and delimiter characters.

The source exercise may require LeetCode Premium. This original explanation and Java reference are free to use here.
Solve on LeetCode ↗

The core insight

Write each string as its character length, a separator, then exactly that many characters. Decode by reading the length before consuming the payload.

Why it works

A length prefix tells the decoder exactly where a payload ends, so separators inside the payload cannot create ambiguity.

The mistake to avoid

Empty list and a list containing an empty string must remain different. Java length counts UTF-16 code units; encoding and decoding use the same convention.

Time: O(total characters + number of strings)Space: O(total characters) output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

class Codec {
    String encode(List<String> words) {
        StringBuilder out = new StringBuilder();
        for (String word : words) out.append(word.length()).append('#').append(word);
        return out.toString();
    }
    List<String> decode(String encoded) {
        List<String> out = new ArrayList<>(); int i = 0;
        while (i < encoded.length()) {
            int marker = encoded.indexOf('#', i);
            int length = Integer.parseInt(encoded.substring(i, marker));
            int start = marker + 1;
            out.add(encoded.substring(start, start + length)); i = start + length;
        }
        return out;
    }
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.