15% off all plans & roadmaps Use code

See plans

Decode String

Updated

TL;DR: Decode String expands each k[text] block into k copies of text, including blocks nested inside other blocks. A stack that saves the prefix and repeat count at each open bracket solves it in one pass.

Problem

Given an encoded string, return its decoded string.

The encoding rule is k[encoded_string]. The encoded_string inside the square brackets repeats exactly k times. The value k is always a positive integer.

You can assume the input is always valid. There are no extra white spaces, and the square brackets are well formed. The original data has no digits. Digits appear only as repeat counts, so inputs like 3a or 2[4] never occur.

The test cases are generated so the output length never exceeds 10^5.

Example 1

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2

Input: s = "3[a2[c]]"
Output: "accaccacc"

Example 3

Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"

Constraints

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

Constraints that matter

  • The output can reach 10^5 characters, so the solution must build strings in work proportional to the output. Rescanning the whole input for every decoded piece is too slow in general.
  • s has at most 30 characters, so the nesting depth is at most 15. A recursive helper or a small explicit stack is safe here.
  • The input is always valid, so you never handle unmatched brackets or a digit with no bracket after it.
  • Repeat counts go up to 300, so a count can have three digits. You must build k one digit at a time with k = k * 10 + digit.

View on LeetCode

Hints

Hint 1

The pattern here is a stack, and the reason is nesting.

Hint 2

Scan for the first ].

Solution

Intuition

The pattern here is a stack, and the reason is nesting. Every [ opens a scope that must finish before the enclosing scope can continue. The most recent open scope is always the first one to close, which is last in, first out order.

Picture a stack of paused notebooks, where each notebook holds the text written so far and a note of how many copies to make. Each ] pops the top notebook and finishes that block before you return to the parent.

The text inside a block is itself a valid encoded string, so the problem nests. You can view each bracket pair as a node in a tree. Its children are the blocks inside it, and its value is the child text repeated k times. Recursion follows that tree directly, and the stack version does the same walk with an explicit list of saved parents.

This is not backtracking, because nothing is undone and no choices are explored. Sorting and dynamic programming do not fit either. The output order is fixed by the input, and no subproblem repeats across different parts of the string. Once you see nested scopes that close in reverse order, the stack is the natural tool.

Watch the pattern animation

Worked example

Input: s = "2[2[b]3[a2[c]]d]"
Output: "bbaccaccaccdbbaccaccaccd"
Explanation: The inner block 3[a2[c]] expands to accaccacc. The text bb comes before the 3[ block, and d comes after it, so the middle of the outer block is bbaccaccaccd. That 12-character middle repeats twice, which gives the 24-character output.

Approach 1: Brute force: rewrite the innermost block

Scan for the first ]. The nearest [ before it opens the innermost block, because no other bracket sits between them. Read the count in front of that [, replace the whole k[...] with the repeated text, and repeat until no [ remains.

This is slow because every replacement rebuilds the whole string. Each block costs a full copy of the text, even the parts that never change. The string can also grow to the full output size, so the copies get large.

The brute force loses track of structure after each rewrite, so it pays for a rescan each time. A stack remembers the outer text instead of rewriting it.

Steps

  1. While the string contains [, find the first ] at index r.
  2. Find the last [ before r. Call its index l.
  3. Walk left from l over digits to find where the count starts at index j.
  4. Parse k from s[j:l].
  5. Replace s[j..r] with s[l+1:r] repeated k times.
  6. Return the string once no [ remains.

Dry run

Input 2[2[b]3[a2[c]]d]. Each round rewrites the innermost block.

  1. First ] is after b. Its [ is after the inner 2. Replace 2[b] with bb. The string becomes 2[bb3[a2[c]]d].
  2. First ] is after c. Its [ is after the 2 in a2. Replace 2[c] with cc. The string becomes 2[bb3[acc]d].
  3. First ] is after acc. Its [ is after 3. Replace 3[acc] with accaccacc. The string becomes 2[bbaccaccaccd].
  4. First ] is at the end. Its [ is after the leading 2. Replace 2[bbaccaccaccd] with the text repeated twice.

The final string is bbaccaccaccdbbaccaccaccd.

Complexity

TimeO(n * (n + L))
SpaceO(n + L)

Let n be the input length and L the output length. There are at most n / 2 bracket pairs, so the loop runs at most n / 2 times. Each round builds a new string, and every intermediate string has length at most n + L, so each round costs O(n + L).

Multiplying gives O(n * (n + L)), which is O(n * L) because L is at least n for valid input. The space holds one string of size n + L at a time.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def decodeString(self, s: str) -> str:
        while '[' in s:
            r = s.index(']')            # first closing bracket
            l = s.rfind('[', 0, r)      # its matching opener
            j = l
            while j > 0 and s[j - 1].isdigit():
                j -= 1
            k = int(s[j:l])
            s = s[:j] + s[l + 1:r] * k + s[r + 1:]
        return s

The Simulation / Backtracking Helper infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Simulation / Backtracking Helper

Part of Stack Patterns

Approach 2: Recursive helper with a shared indexSimulation / Backtracking Helper

What's slow in the brute force: each round rescans the string and rebuilds it. The same block is located and copied again and again.

The insight that fixes it is that a block is a self-contained unit. Parse left to right with one shared index. When you see a count, read the digits, skip the [, and recurse to decode the block.

The recursive call stops at the matching ] and returns its text, and you repeat that text k times. Each character is read once per level of nesting. The helper is a parser that returns decoded text. Nothing is undone, so this is plain recursive descent, not backtracking.

Steps

  1. Keep one index pos that all calls share.
  2. In the helper, collect plain letters into an output buffer until you reach ] or the end of the string.
  3. When you see a digit, read the full number k.
  4. Skip the [, call the helper for the block, and skip the ] it stops at.
  5. Append the returned text k times to the buffer, then continue the loop.
  6. Return the buffer when the helper reaches ] or the end.

Dry run

Input 2[2[b]3[a2[c]]d]. The shared index moves from left to right.

  1. Top call reads 2, skips [, and calls the helper for the block.
  2. That call reads 2, skips [, and calls the helper. The deepest call reads b, hits ], and returns b. The call repeats b twice, giving bb.
  3. Back in the block, the index reads 3, skips [, and recurses. That call reads a, then 2[c] gives cc, so it returns acc. The block repeats it three times to give accaccacc.
  4. The block reads d, then hits ]. It returns bbaccaccaccd.
  5. The top call repeats that text twice and returns bbaccaccaccdbbaccaccaccd.

Complexity

TimeO(L * d)
SpaceO(d + L)

Let n be the input length, L the output length, and d the maximum nesting depth. Each input character is read once, so the scanning costs O(n). Each decoded piece is built by a string repeat, and a character is copied once for each enclosing block it sits in, which is at most d copies.

That gives O(L * d) total work for string building. The recursion depth is d, and the buffers hold O(L) characters, so the space is O(d + L). Here d is at most n / 2 = 15, so the bound is O(L) in practice.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def decodeString(self, s: str) -> str:
        pos = 0

        def helper() -> str:
            nonlocal pos
            out = []
            while pos < len(s) and s[pos] != ']':
                if s[pos].isdigit():
                    k = 0
                    while s[pos].isdigit():
                        k = k * 10 + int(s[pos])
                        pos += 1
                    pos += 1  # skip '['
                    inner = helper()
                    pos += 1  # skip ']'
                    out.append(inner * k)
                else:
                    out.append(s[pos])
                    pos += 1
            return ''.join(out)

        return helper()

Approach 3: One-pass stackOptimal

What's slow in the recursive version: each level returns a string that its parent copies again. The call stack holds the parent state implicitly, and the recursion adds overhead for each block.

The insight that fixes it is to store the parent state on an explicit stack. When you see [, push the text decoded so far and the count that is about to apply to the block. Then reset both and start the block fresh. When you see ], pop the saved text and count, and set the current text to the saved prefix plus the block repeated count times.

The stack holds exactly the open scopes. Each scope is closed once, so the loop is a single pass.

Why it is correct. At every moment, the stack holds exactly the prefix and count of each bracket still open, and cur holds the text of the innermost one. A ] always closes the innermost open bracket, which is the top of the stack, so the popped pair is exactly what that block needs. Once a block is expanded, it becomes part of the parent's text, so every character lands in the right place.

Steps

  1. Create an empty stack of saved pairs (prefix text, count) and set cur to the empty string and k to 0.
  2. For each character, if it is a digit, update k = k * 10 + digit.
  3. If it is [, push (cur, k), then reset cur to empty and k to 0.
  4. If it is ], pop (prev, times) and set cur = prev + cur repeated times.
  5. If it is a letter, append it to cur.
  6. Return cur after the loop.

Dry run

Input 2[2[b]3[a2[c]]d]. The table tracks the state after each character. The stack shows saved pairs as (prefix, count).

StepCharkcurStack after step
122(empty)empty
2[0(empty)[("", 2)]
322(empty)[("", 2)]
4[0(empty)[("", 2), ("", 2)]
5b0b[("", 2), ("", 2)]
6]0bb[("", 2)]
733bb[("", 2)]
8[0(empty)[("", 2), ("bb", 3)]
9a0a[("", 2), ("bb", 3)]
1022a[("", 2), ("bb", 3)]
11[0(empty)[("", 2), ("bb", 3), ("a", 2)]
12c0c[("", 2), ("bb", 3), ("a", 2)]
13]0acc[("", 2), ("bb", 3)]
14]0bbaccaccacc[("", 2)]
15d0bbaccaccaccd[("", 2)]
16]0bbaccaccaccdbbaccaccaccdempty

The final cur is bbaccaccaccdbbaccaccaccd.

Complexity

TimeO(L * d)
SpaceO(d + L)

Let n be the input length, L the output length, and d the maximum nesting depth. The loop reads each of the n characters once, and each [ and ] does O(1) stack work. A character of output is copied once for each enclosing scope it belongs to, which is at most d copies, so string building costs O(L * d).

The stack holds at most d saved pairs, and the output buffer holds O(L) characters, so the space is O(d + L). Since d is at most n / 2 = 15 here, the work is O(L) in practice.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def decodeString(self, s: str) -> str:
        stack = []
        cur = ''
        k = 0
        for ch in s:
            if ch.isdigit():
                k = k * 10 + int(ch)
            elif ch == '[':
                stack.append((cur, k))
                cur = ''
                k = 0
            elif ch == ']':
                prev, times = stack.pop()
                cur = prev + cur * times
            else:
                cur += ch
        return cur

Common mistakes

  • l = s.index('[') picks the outermost opener, not the one matching the first ]. Use the last [ before the closing bracket, as in rfind or lastIndexOf.
  • k = int(ch) in the stack version. It reads only one digit, so 10[a] becomes 0 repeats. Use k = k * 10 + digit for every digit.
  • Not resetting k to 0 after [. The next block inherits the old count, so 2[a]b can repeat b twice. Reset both cur and k after pushing.
  • cur = cur + prev or cur = cur * times + prev when closing a block. The saved prefix must come first, then the repeated block: cur = prev + cur * times.
  • In the recursive helper, forgetting to skip the [ after the count. The helper then reads [ as a letter and the output gains stray brackets.
  • Stopping the recursive helper only at the end of the string. It must also stop at ], or a nested call will consume the parent's closing bracket and everything after it.

Edge cases

  • 1[a] returns a. A count of 1 is valid and must not change the text.
  • 100[a] returns 100 letters a. The count has three digits, so digit accumulation must work for any length.
  • 2[ab3[c]] returns abcccabccc. A letter before a nested block must stay in front of it.
  • abc with no brackets returns abc. The brute force loop never runs, and the stack version returns cur directly.
  • 10[a2[b]] returns 10 copies of abb. The count 10 must not be read as 1 and 0.
  • Nesting 15 levels deep, such as 1[1[...a...]], returns the same text with no change. This is the maximum depth for length 30, so recursion depth is safe.

Follow-ups interviewers ask

What if the input can have unmatched brackets?
I would check both ends of the stack. A ] with an empty stack means an extra closing bracket. A non-empty stack at the end means an unclosed [. The problem promises valid input, so I would raise an error or return an empty result for invalid input, and state the choice to the interviewer.
Can you do it in O(1) extra space?
Not in general. The stack depth can grow to about n / 2, so the saved state needs O(n) space. With n at most 30, that depth is a small constant, but the general bound is O(d). The output itself takes O(L) space and is not counted as extra space.
What if the decoded output is too large to store?
I would stop building the string and yield characters one at a time. Each stack frame stores the block text as a source position and a remaining repeat count. The generator advances through the frames and never builds the full output. Memory then depends on the nesting depth, not on the output length.

Decode String FAQ

What is the time complexity of Decode String?

The optimal stack solution runs in O(L * d) time, where L is the output length and d is the maximum nesting depth. Since d is at most 15 for this problem's length limit, this is effectively O(L). The brute force rewrite is O(n * (n + L)) and is much slower.

Why use a stack for Decode String?

Each open bracket must close before its parent resumes, so the scopes close in last in, first out order. A stack stores the parent's text and count when a block opens. Popping at ] restores the parent without rescanning the input.

Can Decode String be solved in O(1) extra space?

No, not in general. The state for each open block must be stored, and the depth can grow linearly with the input length. The problem limit of 30 keeps that depth small, but the general answer needs O(d) extra space.

Does Decode String need recursion?

No. The stack version does the same nested decoding with an explicit list of saved states. The recursive helper is also correct, and it is often easier to explain out loud. Both use space proportional to the nesting depth.

Asked at

See which companies ask this — Pro

Practise it