Decode String

Expand a string such as 3[a2[c]], where a number before brackets repeats the text inside them.

Given an encoded string s, return its decoded form. The encoding has one rule: k[text] stands for text written k times in a row, where k is a whole number. The text inside the brackets can itself contain encoded parts, so brackets can sit inside brackets. Letters outside any brackets stay as they are.

Example 1
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2
Input: s = "3[a2[c]]"
Output: "accaccacc"
Explanation: the inner "2[c]" becomes "cc", so the outer part is "3[acc]".
Solution

The Idea

The encoding works like brackets in arithmetic. In 3 × (1 + 2 × (4 + 5)) you cannot finish the outer bracket until the inner one is done. Example 1 has no bracket inside another, so each part can be finished on its own: 3[a] gives aaa, 2[bc] gives bcbc, and together they make aaabcbc.

Example 2 is where it gets interesting. Read 3[a2[c]] from left to right. After 3[a we know the outer part will be repeated 3 times, and that it starts with a. Then 2[ opens a new part before the outer one is finished. So what must we keep in mind while we decode the inner part, and when do we need it back?

We need two things: the count 3, and the text a that was built before the inner bracket opened. We need them back as soon as the inner part closes. The inner part was opened last but closes first, and that order holds at any depth.

A pile where you can only add or take the top item has exactly this order: the last item put on is the first taken off. It is called a stack. Putting an item on top is a push, and taking the top item off is a pop. Look at the picture below. Each stack entry is a pair: a count, and the text built before its bracket opened. cur is the text being built right now.

Decoding 3[a2[c]]. After 3[a the stack holds (3, "") and cur is a. After 2[c the stack also holds (2, "a") on top and cur is c. The first ] pops (2, "a") and cur becomes acc. The second ] pops (3, "") and cur becomes accaccacc.

In the column labelled "after 3[a", the first [ has pushed (3, ""): count 3, and no text before it. cur then started empty and has collected a. In "after 2[c", the second [ has pushed (2, "a") on top, and cur started again and holds c.

Now the closing brackets arrive. In "after the first ]", the top pair (2, "a") is popped: a plus c twice gives acc. In "after the second ]", (3, "") is popped: nothing plus acc three times gives accaccacc, the answer.

So each [ saves where we were, and each ] finishes the innermost open part and returns to the saved place. One pass from left to right decodes the whole string.

Solution Approach

Turning the stack idea into code means settling three things: how to read a count, what to save at [, and what to do at ]. Before those, a slower way without a stack, and after them an optional recursive version.

Expanding one bracket at a time

Why not just find an innermost bracket, such as 2[c], replace it with cc, and repeat until no brackets are left? It gives the right answer, but each replacement builds a new copy of the whole string. A string with many brackets is copied once per bracket, even the parts far away from it. The stack never rebuilds text it has finished with.

Reading a count

How many characters long is a count? It can have several digits, as in 10[a]. So the count k is built digit by digit: each new digit gives k = k * 10 + digit. For 10 that is 1, then 1 × 10 + 0 = 10. A [ always comes right after its count, so that is the moment the count is complete.

Saving the outer state at [

What goes on the stack? The pair from the picture: the count k, and cur, the text built so far. Then cur starts empty for the inner text, and k goes back to 0 for the next count. Rather than define a small pair class, the code keeps two stacks that always move together: counts for the numbers and outer for the texts.

Finishing a part at ]

What happens when a bracket closes? cur now holds the complete inner text. Pop the count and the outer text, repeat the inner text that many times, and append it to the outer text, which becomes cur again. A letter outside any brackets simply goes onto cur, so when the string ends, cur is the answer.

Optional: a recursive version

A method that calls itself can do the same work. On [ it calls itself to decode the inside, and that call returns at the matching ]. Java remembers each unfinished call and its local variables, which plays the part of the stack. All the calls must agree on how far into s they have read, which takes some care. The two stacks avoid that.

Java Solution

The method decodeString works in these steps:

  1. First, create the two stacks: counts for the repeat counts and outer for the text built before each [. Both are ArrayDeque objects, Java's usual choice for a stack. Start cur as an empty StringBuilder and the count k at 0.
  2. Read the string one character c at a time with a loop. A digit extends the count: k = k * 10 + (c - '0').
  3. At [, push k onto counts and cur onto outer. Then give cur a new empty builder and set k back to 0.
  4. At ], keep the finished inner text as inner. Pop the outer text into cur, and append inner.repeat(counts.pop()) to it.
  5. Any other character is a letter, so append it to cur. After the loop, return cur as a string.

The main method decodes both examples, two parts followed by plain letters, a bracket inside a bracket with letters on both sides, a two-digit count, and a string with no brackets.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class DecodeString {

    public static String decodeString(String s) {
        Deque<Integer> counts = new ArrayDeque<>();
        Deque<StringBuilder> outer = new ArrayDeque<>();   // text built before each '['
        StringBuilder cur = new StringBuilder();
        int k = 0;
        for (char c : s.toCharArray()) {
            if (Character.isDigit(c)) {
                k = k * 10 + (c - '0');       // counts can have several digits
            } else if (c == '[') {
                counts.push(k);               // remember the count and the text so far
                outer.push(cur);
                cur = new StringBuilder();    // start the inner text
                k = 0;
            } else if (c == ']') {
                String inner = cur.toString();
                cur = outer.pop();            // back to the text before '['
                cur.append(inner.repeat(counts.pop()));
            } else {
                cur.append(c);
            }
        }
        return cur.toString();
    }

    public static void main(String[] args) {
        System.out.println(decodeString("3[a]2[bc]"));
        System.out.println(decodeString("3[a2[c]]"));
        System.out.println(decodeString("2[abc]3[cd]ef"));
        System.out.println(decodeString("2[a2[b]c]"));
        System.out.println(decodeString("10[a]"));
        System.out.println(decodeString("abc"));
    }
}

Running it prints:

Output
aaabcbc
accaccacc
abcabccdcdcdef
abbcabbc
aaaaaaaaaa
abc

aaabcbc and accaccacc at the top match Examples 1 and 2. The fourth line comes from 2[a2[b]c]: the inner 2[b] becomes bb and joins a and c into abbc, and only then is it repeated, giving abbcabbc. The last line shows that abc, with no brackets, comes back unchanged.

Look at the fifth line: ten a characters from 10[a]. Here the digit-by-digit count matters. If the digit line were k = c - '0' instead, the 0 would overwrite the 1, and that line prints empty, because the text is repeated 0 times.

Complexity

Let n be the length of s, L the length of the decoded string, and d the deepest nesting of brackets.

  • Time: O(n + d × L). The loop reads each of the n characters once. Each ] copies its expanded text, so a letter of the answer that sits inside d brackets is copied once at every level on its way out.
  • Space: O(L + d). The builders together hold no more than the characters of the answer, and each stack has one entry per open bracket, so at most d entries.

Basic Calculator II also reads an expression in one pass from left to right.