Decode String

Medium

Topics
StringStack

Given an encoded string s following the rule k[encoded] meaning the bracketed part repeats k times, return the decoded string.

Example 1

in3[a]2[bc]
outaaabcbc
bracket
Brackets nest, so the repeat count and the text being built both have to be remembered per level — two stacks, pushed at [ and popped at ]. Counts can be multi-digit, so they are accumulated rather than read one character at a time. Result: aaabcbc.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2

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

Constraints

  • 1 <= s.length <= 30
  • Digits are only for repeat counts.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The encoding nests — 3[a2[c]] has a repeat inside a repeat — so the decoder has to suspend what it is building, handle the inner group, then resume. Suspend-and-resume is a stack.

Two things must be saved when a [ opens: the string built so far at this level, and the repeat count that applies to the group about to start. On the matching ], pop both, multiply the inner result by the count, and append it to the saved prefix.

The multi-digit parse matters: 12[a] means twelve repeats, so digits accumulate with num = num * 10 + digit rather than being read one at a time.

Approach

  1. Keep current (the string at this level) and num (the pending count).
  2. Digit: extend num.
  3. [: push (current, num), reset both.
  4. ]: pop (prefix, k), set current = prefix + current * k.
  5. Letter: append to current.

Dry Run

s = "3[a2[c]]"

3      num=3
[      push ("", 3)          current=""   num=0
a      current="a"
2      num=2
[      push ("a", 2)         current=""   num=0
c      current="c"
]      pop ("a",2) -> current = "a" + "c"*2 = "acc"
]      pop ("",3)  -> current = "" + "acc"*3 = "accaccacc"

answer "accaccacc"

The inner ] is the instructive step: current holds only "c", because the [ reset it, and the saved "a" is what the outer level had accumulated.

Complexity

  • Time — O(length of the output): every character of the result is produced once. Expressing it in terms of the input is misleading — 10[10[10[a]]] is 14 characters of input and a thousand of output, so the output length is the honest measure.
  • Space — O(length of the output): the stack holds one saved prefix per nesting level, and those prefixes together are bounded by the result.

Common Pitfalls

  • Reading digits one at a time, so 12[a] becomes one repeat then two.
  • Pushing the count but not the prefix. The text before [ belongs to the outer level and must survive the inner group.
  • Appending before multiplying on ]. The count applies to the inner group only, not to the prefix.
  • Resetting num but not current on [, which duplicates the prefix into the inner group.
  • Trying to decode with a regex or a single pass without a stack. Nesting is unbounded, so neither works.

Full Solution — all languages

class Solution:
    def decodeString(self, s):
        stack = []
        cur = ""
        num = 0
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
            elif c == "[":
                stack.append((cur, num))
                cur = ""
                num = 0
            elif c == "]":
                prev, k = stack.pop()
                cur = prev + cur * k
            else:
                cur += c
        return cur
SensAI
Beta
Tap the mic to stop voice mode