Decode String
Expand nested patterns like 2[ab3[c]] by saving the outer text and count on a stack at every bracket.
The problem
You get an encoded string in which k[text] stands for text repeated k times, and these groups can be nested inside each other. Return the fully decoded string. You can assume the input is well formed: brackets match, digits only appear as repeat counts, and the decoded string has at most 100,000 characters.
Input s = "2[ab3[c]]d"
Output "abcccabcccd"
The inner `3[c]` becomes `ccc`, so the group reads `abccc`; repeat it twice and add `d`.
Input s = "x12[y]"
Output "xyyyyyyyyyyyy"
A count can have more than one digit: twelve copies of `y` follow the `x`.
Key constraint: Groups can be nested several levels deep, and a repeat count can have more than one digit.
How to spot the pattern
- Nested brackets, where the inner part must be finished before the outer part can use it.
- When a bracket closes, you need to get back to exactly the state you had when it opened.
The idea
When you meet [, an inner piece of text starts, but you must not forget the text built so far or the count that applies to the new piece. Push both onto a stack and start the inner text from empty. When you meet ], pop the saved text and count, and attach count copies of the inner text to the saved text. Because the group opened last always closes first, a stack handles any depth of nesting.
Brute force: Repeatedly find an innermost group with no brackets inside, expand it and rebuild the whole string, which redoes the work on the entire string for every group.
Step by step
- 1Keep the current text, the number being read and a stack of (text before the group, repeat count) pairs.
- 2For a digit, extend the number:
num = num * 10 + digit. - 3For
[, push (current text,num) and reset the current text to empty andnumto 0. - 4For
], pop (text before, count) and make the current text equal to the text before pluscountcopies of the current text. - 5For a letter, append it to the current text, and after the last character return the current text.
See the pattern move
The stacks pattern on a small example. Step through it, or press play.
Code
class Solution:
def decodeString(self, s: str) -> str:
stack = [] # (text before this group, repeat count)
parts = [] # the current text, kept as a list of pieces and joined when needed
num = 0
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch == "[":
stack.append((parts, num))
parts, num = [], 0
elif ch == "]":
before, count = stack.pop()
before.append("".join(parts) * count)
parts = before
else:
parts.append(ch)
return "".join(parts)Complexity
Time
O(n + m * d)
Space
O(n + m)
n is the input length, m the output length and d the deepest nesting: each decoded group can be copied once more by every group around it. The saved texts are all pieces of the output.
Watch out for
- Reading only one digit for the count, which treats
12[y]as a stray1followed by2[y]. - Forgetting to reset the number to 0 after pushing it at
[, so the next count keeps the old digits. - Attaching the repeated text to a fresh string after
]: it belongs after the text that was saved on the stack.
Follow-up questions
Can you solve it with recursion instead of an explicit stack?
Yes: a helper reads from a shared index and builds text until it meets ]; when it meets k[, it calls itself for the inner text and repeats the result k times. The call stack does the job of your stack.
What if the decoded string could be far too large to build, and you only need the character at one position?
Work with lengths instead of text: compute how long each group decodes to, then walk back through the structure, reducing the position with position % length at every repeat until it lands on a single letter.
In Hinglish
`[` aaye toh ab tak ka text aur count stack mein save karo aur naya text shuru karo. `]` aaye toh save kiya hua text wapas lo aur andar wala text count baar uske peeche jod do.