Browse curriculum

Decode String (LeetCode 394)

Decode String (LeetCode 394): decode an encoded string with nested repetition rules.

Problem Understanding

You are given an encoded string where k[encoded_string] means the encoded_string inside the brackets is repeated exactly k times. You may assume the input string is always valid.

Example:

  • Input: 3[a]2[bc] -> Output: aaabcbc
  • Input: 3[a2[c]] -> Output: accaccacc (Nested!)

Algorithm Strategy

We use a Stack to handle the nested nature of the problem.

  1. Initialize an empty stack.
  2. Iterate through the string character by character.
  3. If the char is NOT ], push it to the stack.
  4. If the char IS ], we must start decoding:
    • Pop characters until we find [. This is the string_to_repeat.
    • Pop the [.
    • Pop numbers to form k (the repetition count).
    • Repeat string_to_repeat k times and Push it back to the stack.
  5. Finally, join the stack to get the result.

Interactive Visualization

"3[a2[c]]"

READ

encoded

i

3

0

[

1

a

2

2

3

[

4

c

5

]

6

]

7

stack

empty

chunk

:

k

:

Result

:

 

Read '3' at 0

Next

'3' is not ']': push it

Free preview: the first 8 of 24 steps

Encoded

Visualize how the stack builds nested strings from the inside out.

Dry Run

Input: 3[a2[c]]

Char Action Stack
3,[,a,2,[,c Push all ['3', '[', 'a', '2', '[', 'c']
] Pop until [. K=2. Repeat c x2. ['3', '[', 'a', 'cc']
] Pop until [. String=acc. K=3. Repeat acc x3. ['accaccacc']

Result: accaccacc

Edge Cases & Common Mistakes

  • Multi-digit K: e.g., 10[a]. Ensure you parse the full number.
  • Empty Brackets: 3[] -> Empty string.
  • No Brackets: abc -> abc.

Solution

Stack Implementation.

Decode String Code
1var decodeString = function(s) {
2 const stack = [];
3 for (const ch of s) {
4 if (ch !== ']') {
5 stack.push(ch);
6 } else {
7 let chunk = '';
8 while (stack[stack.length - 1] !== '[') {
9 chunk = stack.pop() + chunk;
10 }
11 stack.pop(); // drop "["
12 let k = '';
13 while (stack.length > 0 && /^\d$/.test(stack[stack.length - 1])) {
14 k = stack.pop() + k;
15 }
16 stack.push(chunk.repeat(Number(k)));
17 }
18 }
19 return stack.join('');
20};

Decode String in Python, Java, C++, TypeScript and C

Decode String in Python
class Solution:
    def decodeString(self, s: str) -> str:
        stack = []
        for ch in s:
            if ch != "]":
                stack.append(ch)
            else:
                chunk = ""
                while stack[-1] != "[":
                    chunk = stack.pop() + chunk
                stack.pop()  # drop "["
                k = ""
                while stack and stack[-1].isdigit():
                    k = stack.pop() + k
                stack.append(chunk * int(k))
        return "".join(stack)
Decode String in Java
class Solution {
    public String decodeString(String s) {
        Deque<String> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c != ']') {
                stack.push(String.valueOf(c));
            } else {
                StringBuilder chunk = new StringBuilder();
                while (!stack.peek().equals("[")) {
                    chunk.insert(0, stack.pop());
                }
                stack.pop(); // drop "["
                StringBuilder k = new StringBuilder();
                while (!stack.isEmpty() && isDigit(stack.peek())) {
                    k.insert(0, stack.pop());
                }
                stack.push(chunk.toString().repeat(Integer.parseInt(k.toString())));
            }
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) result.append(stack.pollLast());
        return result.toString();
    }

    private boolean isDigit(String part) {
        return part.length() == 1 && Character.isDigit(part.charAt(0));
    }
}
Decode String in C++
class Solution {
public:
    string decodeString(string s) {
        vector<string> stack;
        for (char c : s) {
            if (c != ']') {
                stack.push_back(string(1, c));
            } else {
                string chunk = "";
                while (stack.back() != "[") {
                    chunk = stack.back() + chunk;
                    stack.pop_back();
                }
                stack.pop_back(); // drop "["
                string k = "";
                while (!stack.empty() && stack.back().size() == 1 && isdigit(stack.back()[0])) {
                    k = stack.back() + k;
                    stack.pop_back();
                }
                string repeated = "";
                for (int times = stoi(k); times > 0; times--) repeated += chunk;
                stack.push_back(repeated);
            }
        }
        string result = "";
        for (const string& part : stack) result += part;
        return result;
    }
};
Decode String in TypeScript
function decodeString(s: string): string {
    const stack: string[] = [];
    for (const ch of s) {
        if (ch !== ']') {
            stack.push(ch);
        } else {
            let chunk = '';
            while (stack[stack.length - 1] !== '[') {
                chunk = stack.pop()! + chunk;
            }
            stack.pop(); // drop "["
            let k = '';
            while (stack.length > 0 && /^\d$/.test(stack[stack.length - 1])) {
                k = stack.pop()! + k;
            }
            stack.push(chunk.repeat(Number(k)));
        }
    }
    return stack.join('');
}
Decode String in C
static char* join(const char* a, const char* b) {
    char* out = malloc(strlen(a) + strlen(b) + 1);
    strcpy(out, a);
    strcat(out, b);
    return out;
}

char* decodeString(char* s) {
    int n = strlen(s);
    char** stack = malloc((n + 1) * sizeof(char*));
    int top = 0;
    for (int i = 0; i < n; i++) {
        char ch = s[i];
        if (ch != ']') {
            char one[2] = { ch, '\0' };
            stack[top++] = join(one, "");
        } else {
            char* chunk = join("", "");
            while (strcmp(stack[top - 1], "[") != 0) {
                char* next = join(stack[--top], chunk);
                free(stack[top]);
                free(chunk);
                chunk = next;
            }
            free(stack[--top]); // drop "["
            char* k = join("", "");
            while (top > 0 && strlen(stack[top - 1]) == 1 && isdigit(stack[top - 1][0])) {
                char* next = join(stack[--top], k);
                free(stack[top]);
                free(k);
                k = next;
            }
            char* repeated = join("", "");
            for (int times = atoi(k); times > 0; times--) {
                char* next = join(repeated, chunk);
                free(repeated);
                repeated = next;
            }
            free(k);
            free(chunk);
            stack[top++] = repeated;
        }
    }
    char* result = join("", "");
    for (int j = 0; j < top; j++) {
        char* next = join(result, stack[j]);
        free(result);
        free(stack[j]);
        result = next;
    }
    free(stack);
    return result;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Push until "]"

    Push every character that is not a closing bracket.

  2. Collect the group

    On "]", pop chunks into the group text until "[", drop it, and pop the digits below into k.

  3. Push it back

    Push the group text repeated k times, and join the stack at the end.

Frequently asked questions

How does a stack decode nested strings like 3[a2[c]]?

Push characters until a "]". Then pop chunks back to the "[", drop it, pop the digits for k, and push the chunk repeated k times. Inner groups close first, so their decoded text is already one chunk when the outer group repeats it.


How are multi-digit counts like 10[x] handled?

The digits are pushed one at a time, so after dropping "[" the code keeps popping while the top is a digit and prepends each one, giving "10".


What is the complexity of Decode String?

Proportional to the input length n plus the decoded length L for the pushes and pops; building each chunk by prepending can add up to O(n · L) character copies.

New to the technique behind this problem? Watch it run step by step:

Stack Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description