Decode String (LeetCode 394): Solution and Explanation

Medium
String
Stack
Recursion

A string is encoded with the rule k[text], meaning text repeated k times, and these patterns can be nested. Given an encoded string, return the fully expanded version.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

If there were no nesting, you could scan for a number, the bracketed text after it, and repeat it. Nesting is what makes this interesting: in 3[a2[c]], you cannot repeat the outer part until you know what the inner part expands to. Any time an inner structure must be finished before the outer one can be completed, that is a sign to reach for a stack or recursion.

Think about what you need to remember when you hit an opening bracket. You are about to start building a brand new piece of text, the part inside the brackets. But you must not forget two things: the text you had built so far at the outer level, and the number that came right before the bracket, which says how many times to repeat the inner text. So on [, push the pair (current_str, current_num) onto a stack and start fresh with an empty string and a zero count.

On ], the inner text is complete. Pop the saved pair, repeat the inner text the saved number of times, and append it to the saved outer text. That result becomes the new current string, and you continue at the outer level as if the whole bracketed group were ordinary letters. Digits simply accumulate into current_num (so multi-digit counts like 12 work), and letters append to current_str. When the scan ends, the stack is empty and current_str holds the answer.

Approach: Stack of saved string and count

  1. Initialize an empty stack, an empty current_str, and current_num = 0.
  2. For a digit, update current_num = current_num * 10 + int(char) so multi-digit counts are read correctly.
  3. For [, push (current_str, current_num) onto the stack, then reset current_str to empty and current_num to 0.
  4. For ], pop (prev_str, num) and set current_str = prev_str + current_str * num.
  5. For any letter, append it to current_str.
  6. After the loop, return current_str.

Step-by-step example

s = "3[a2[c]]"
  1. Read 3, so current_num = 3. Read [, push ("", 3), and reset to an empty string and 0.
  2. Read a, so current_str = "a". Read 2, so current_num = 2.
  3. Read [, push ("a", 2), and reset. Read c, so current_str = "c".
  4. Read ], pop ("a", 2), and build "a" + "cc" = "acc".
  5. Read the final ], pop ("", 3), and build "" + "acc" repeated 3 times = "accaccacc".
  6. The input is finished, so the function returns "accaccacc".

Code: Python, Java, C++

1class Solution:
2    def decodeString(self, s: str) -> str:
3        stack = []
4        current_str = ""
5        current_num = 0
6
7        for char in s:
8            if char.isdigit():
9                current_num = current_num * 10 + int(char)
10            elif char == '[':
11                stack.append((current_str, current_num))
12                current_str = ""
13                current_num = 0
14            elif char == ']':
15                prev_str, num = stack.pop()
16                current_str = prev_str + current_str * num
17            else:
18                current_str += char
19
20        return current_str

Time and space complexity

Time

O(d × L)

Here L is the length of the decoded output and d is the maximum nesting depth. Each closing bracket builds a new string no longer than the output, and a character of the output can be copied once per enclosing level, so the work is bounded by d × L and is close to linear for shallow nesting.

Space

O(L)

The stack holds at most d saved prefixes, and together with the current string they never exceed the length of the final output.

Other approaches

Recursive descent (time O(d × L), space O(L))

Write a helper that reads from a shared index, building a string until it hits ] or the end. When it sees a number followed by [, it recurses to decode the inner part, then repeats it. It mirrors the grammar of the encoding directly and many people find it more readable, at the cost of recursion depth equal to the nesting depth.

Common mistakes

  • Reading only single-digit counts. Inputs like 12[a] require accumulating digits with current_num * 10 + digit.
  • Forgetting to reset current_num to 0 after pushing at [, which makes the next count start from the previous one.
  • Pushing only the count and not the outer string. On ] you then lose the text that came before the bracket.
  • In Java, concatenating with String + inside loops. Use StringBuilder for the current string and the saved strings, or the solution slows down sharply on large outputs.

Frequently asked questions

Why use a stack for Decode String?

Brackets nest, and an inner group must be fully decoded before the outer group can be repeated. A stack remembers the outer context at each opening bracket and restores it in the right order at each closing bracket.

How do you handle multi-digit numbers like 100[a]?

Accumulate digits as you read them with current_num = current_num * 10 + digit, and only consume the number when you reach the opening bracket.

Stack or recursion for Decode String?

They are equivalent; the recursive version uses the call stack instead of an explicit one. The explicit stack avoids recursion limits, while recursion follows the nested structure more naturally.