Decode String
On this page
Problem statement
Expand a compressed string. In the input,
k[text]means "textrepeatedktimes", wherekis a positive integer and can have several digits. Brackets can be nested, and plain letters can appear anywhere. The input is always well formed. Return the fully expanded string.
A compact test of stack thinking: every [ opens a new level, and every ] closes the innermost one. Variants show up as "expand a template", "unzip a run-length format" or "evaluate nested repeats". Original problem: LeetCode 394.
Example
![The innermost group 3[c] expands first; its result becomes part of the outer group.](https://storage.ghost.io/c/cc/3d/cc3dd2ec-1125-4515-87dd-11389c0d3c50/content/images/2026/11/000-41d590d3-24.png)
Input: "2[ab3[c]]x"
Output: "abcccabcccx"
Input: "12[a]"
Output: "aaaaaaaaaaaa" # counts can have more than one digit
Input: "sys2[tem]"
Output: "systemtem" # letters before a group stay in front
Constraints (assumed)
- 1 ≤ length of the input ≤ 30; counts are between 1 and 300.
- The input contains only lowercase letters, digits and square brackets, and is valid.
- The output fits in memory (its length is at most 10⁵).
What this question tests
- Recognising nesting and reaching for a stack (or recursion).
- Parsing details: multi-digit numbers, letters before and after groups.
- Building strings efficiently rather than re-copying them on every character.
Questions to ask first
- Can the count have more than one digit? (Here: yes.)
- Is the input always valid, with matched brackets and a number before every
[? (Here: yes.) - Can a count be 0? (Here: no. If yes, the group simply disappears.)
- How large can the output get? Repeats multiply, so a short input can expand to something huge.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.