15% off all plans & roadmaps Use code
See plansDecode String
- LeetCode 394
- Medium
- Stack Patterns
- Simulation / Backtracking Helper
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 <= 30sconsists of lowercase English letters, digits, and square brackets'[]'.sis guaranteed to be a valid input.- All the integers in
sare 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.
shas 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
kone digit at a time withk = k * 10 + digit.
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.
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
- While the string contains
[, find the first]at indexr. - Find the last
[beforer. Call its indexl. - Walk left from
lover digits to find where the count starts at indexj. - Parse
kfroms[j:l]. - Replace
s[j..r]withs[l+1:r]repeatedktimes. - Return the string once no
[remains.
Dry run
Input 2[2[b]3[a2[c]]d]. Each round rewrites the innermost block.
- First
]is afterb. Its[is after the inner2. Replace2[b]withbb. The string becomes2[bb3[a2[c]]d]. - First
]is afterc. Its[is after the2ina2. Replace2[c]withcc. The string becomes2[bb3[acc]d]. - First
]is afteracc. Its[is after3. Replace3[acc]withaccaccacc. The string becomes2[bbaccaccaccd]. - First
]is at the end. Its[is after the leading2. Replace2[bbaccaccaccd]with the text repeated twice.
The final string is bbaccaccaccdbbaccaccaccd.
Complexity
| Time | O(n * (n + L)) |
|---|---|
| Space | O(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 sJavaTested in our runner
import java.util.*;
class Solution {
public String decodeString(String s) {
while (s.indexOf('[') >= 0) {
int r = s.indexOf(']');
int l = s.lastIndexOf('[', r);
int j = l;
while (j > 0 && Character.isDigit(s.charAt(j - 1))) j--;
int k = Integer.parseInt(s.substring(j, l));
s = s.substring(0, j) + s.substring(l + 1, r).repeat(k) + s.substring(r + 1);
}
return s;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
string decodeString(string s) {
while (s.find('[') != string::npos) {
size_t r = s.find(']');
size_t l = s.rfind('[', r);
size_t j = l;
while (j > 0 && s[j - 1] >= '0' && s[j - 1] <= '9') j--;
int k = stoi(s.substr(j, l - j));
string mid;
for (int t = 0; t < k; t++) mid += s.substr(l + 1, r - l - 1);
s = s.substr(0, j) + mid + s.substr(r + 1);
}
return s;
}
};JavaScriptTested in our runner
var decodeString = function(s) {
while (s.includes('[')) {
const r = s.indexOf(']');
const l = s.lastIndexOf('[', r);
let j = l;
while (j > 0 && s[j - 1] >= '0' && s[j - 1] <= '9') j--;
const k = parseInt(s.substring(j, l), 10);
s = s.substring(0, j) + s.substring(l + 1, r).repeat(k) + s.substring(r + 1);
}
return s;
};GoTested in our runner
import (
"strconv"
"strings"
)
func decodeString(s string) string {
for strings.Contains(s, "[") {
r := strings.Index(s, "]")
l := strings.LastIndex(s[:r], "[")
j := l
for j > 0 && s[j-1] >= '0' && s[j-1] <= '9' {
j--
}
k, _ := strconv.Atoi(s[j:l])
s = s[:j] + strings.Repeat(s[l+1:r], k) + s[r+1:]
}
return s
}C#Tested in our runner
public class Solution {
public string decodeString(string s) {
while (s.Contains('[')) {
int r = s.IndexOf(']');
int l = s.LastIndexOf('[', r);
int j = l;
while (j > 0 && char.IsDigit(s[j - 1])) j--;
int k = int.Parse(s.Substring(j, l - j));
string mid = string.Concat(Enumerable.Repeat(s.Substring(l + 1, r - l - 1), k));
s = s.Substring(0, j) + mid + s.Substring(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 infographicSolution 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
- Keep one index
posthat all calls share. - In the helper, collect plain letters into an output buffer until you reach
]or the end of the string. - When you see a digit, read the full number
k. - Skip the
[, call the helper for the block, and skip the]it stops at. - Append the returned text
ktimes to the buffer, then continue the loop. - 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.
- Top call reads
2, skips[, and calls the helper for the block. - That call reads
2, skips[, and calls the helper. The deepest call readsb, hits], and returnsb. The call repeatsbtwice, givingbb. - Back in the block, the index reads
3, skips[, and recurses. That call readsa, then2[c]givescc, so it returnsacc. The block repeats it three times to giveaccaccacc. - The block reads
d, then hits]. It returnsbbaccaccaccd. - The top call repeats that text twice and returns
bbaccaccaccdbbaccaccaccd.
Complexity
| Time | O(L * d) |
|---|---|
| Space | O(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()JavaTested in our runner
import java.util.*;
class Solution {
public String decodeString(String s) {
return helper(s, new int[]{0});
}
private String helper(String s, int[] pos) {
StringBuilder sb = new StringBuilder();
while (pos[0] < s.length() && s.charAt(pos[0]) != ']') {
char c = s.charAt(pos[0]);
if (Character.isDigit(c)) {
int k = 0;
while (Character.isDigit(s.charAt(pos[0]))) {
k = k * 10 + (s.charAt(pos[0]) - '0');
pos[0]++;
}
pos[0]++; // skip '['
String inner = helper(s, pos);
pos[0]++; // skip ']'
sb.append(inner.repeat(k));
} else {
sb.append(c);
pos[0]++;
}
}
return sb.toString();
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
string decodeString(string s) {
size_t pos = 0;
return helper(s, pos);
}
private:
string helper(const string &s, size_t &pos) {
string out;
while (pos < s.size() && s[pos] != ']') {
if (s[pos] >= '0' && s[pos] <= '9') {
int k = 0;
while (s[pos] >= '0' && s[pos] <= '9') {
k = k * 10 + (s[pos] - '0');
pos++;
}
pos++; // skip '['
string inner = helper(s, pos);
pos++; // skip ']'
for (int t = 0; t < k; t++) out += inner;
} else {
out += s[pos];
pos++;
}
}
return out;
}
};JavaScriptTested in our runner
var decodeString = function(s) {
let pos = 0;
const helper = () => {
let out = '';
while (pos < s.length && s[pos] !== ']') {
const c = s[pos];
if (c >= '0' && c <= '9') {
let k = 0;
while (s[pos] >= '0' && s[pos] <= '9') {
k = k * 10 + (s.charCodeAt(pos) - 48);
pos++;
}
pos++; // skip '['
const inner = helper();
pos++; // skip ']'
out += inner.repeat(k);
} else {
out += c;
pos++;
}
}
return out;
};
return helper();
};GoTested in our runner
import (
"strings"
)
func decodeString(s string) string {
pos := 0
var helper func() string
helper = func() string {
var sb strings.Builder
for pos < len(s) && s[pos] != ']' {
c := s[pos]
if c >= '0' && c <= '9' {
k := 0
for s[pos] >= '0' && s[pos] <= '9' {
k = k*10 + int(s[pos]-'0')
pos++
}
pos++ // skip '['
inner := helper()
pos++ // skip ']'
sb.WriteString(strings.Repeat(inner, k))
} else {
sb.WriteByte(c)
pos++
}
}
return sb.String()
}
return helper()
}C#Tested in our runner
public class Solution {
public string decodeString(string s) {
int pos = 0;
return helper(s, ref pos);
}
private string helper(string s, ref int pos) {
string res = "";
while (pos < s.Length && s[pos] != ']') {
if (char.IsDigit(s[pos])) {
int k = 0;
while (char.IsDigit(s[pos])) {
k = k * 10 + (s[pos] - '0');
pos++;
}
pos++; // skip '['
string inner = helper(s, ref pos);
pos++; // skip ']'
res += string.Concat(Enumerable.Repeat(inner, k));
} else {
res += s[pos];
pos++;
}
}
return res;
}
}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
- Create an empty stack of saved pairs (prefix text, count) and set
curto the empty string andkto 0. - For each character, if it is a digit, update
k = k * 10 + digit. - If it is
[, push(cur, k), then resetcurto empty andkto 0. - If it is
], pop(prev, times)and setcur = prev + cur repeated times. - If it is a letter, append it to
cur. - Return
curafter 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).
| Step | Char | k | cur | Stack after step |
|---|---|---|---|---|
| 1 | 2 | 2 | (empty) | empty |
| 2 | [ | 0 | (empty) | [("", 2)] |
| 3 | 2 | 2 | (empty) | [("", 2)] |
| 4 | [ | 0 | (empty) | [("", 2), ("", 2)] |
| 5 | b | 0 | b | [("", 2), ("", 2)] |
| 6 | ] | 0 | bb | [("", 2)] |
| 7 | 3 | 3 | bb | [("", 2)] |
| 8 | [ | 0 | (empty) | [("", 2), ("bb", 3)] |
| 9 | a | 0 | a | [("", 2), ("bb", 3)] |
| 10 | 2 | 2 | a | [("", 2), ("bb", 3)] |
| 11 | [ | 0 | (empty) | [("", 2), ("bb", 3), ("a", 2)] |
| 12 | c | 0 | c | [("", 2), ("bb", 3), ("a", 2)] |
| 13 | ] | 0 | acc | [("", 2), ("bb", 3)] |
| 14 | ] | 0 | bbaccaccacc | [("", 2)] |
| 15 | d | 0 | bbaccaccaccd | [("", 2)] |
| 16 | ] | 0 | bbaccaccaccdbbaccaccaccd | empty |
The final cur is bbaccaccaccdbbaccaccaccd.
Complexity
| Time | O(L * d) |
|---|---|
| Space | O(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 curJavaTested in our runner
import java.util.*;
class Solution {
public String decodeString(String s) {
Deque<String> prevs = new ArrayDeque<>();
Deque<Integer> counts = new ArrayDeque<>();
String cur = "";
int k = 0;
for (char ch : s.toCharArray()) {
if (Character.isDigit(ch)) {
k = k * 10 + (ch - '0');
} else if (ch == '[') {
prevs.push(cur);
counts.push(k);
cur = "";
k = 0;
} else if (ch == ']') {
String prev = prevs.pop();
int times = counts.pop();
cur = prev + cur.repeat(times);
} else {
cur += ch;
}
}
return cur;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
string decodeString(string s) {
stack<pair<string, int>> st;
string cur;
int k = 0;
for (char ch : s) {
if (ch >= '0' && ch <= '9') {
k = k * 10 + (ch - '0');
} else if (ch == '[') {
st.push(make_pair(cur, k));
cur.clear();
k = 0;
} else if (ch == ']') {
pair<string, int> top = st.top();
st.pop();
string rep;
for (int t = 0; t < top.second; t++) rep += cur;
cur = top.first + rep;
} else {
cur += ch;
}
}
return cur;
}
};JavaScriptTested in our runner
var decodeString = function(s) {
const stack = [];
let cur = '';
let k = 0;
for (const ch of s) {
if (ch >= '0' && ch <= '9') {
k = k * 10 + (ch.charCodeAt(0) - 48);
} else if (ch === '[') {
stack.push([cur, k]);
cur = '';
k = 0;
} else if (ch === ']') {
const [prev, times] = stack.pop();
cur = prev + cur.repeat(times);
} else {
cur += ch;
}
}
return cur;
};GoTested in our runner
import (
"strings"
)
func decodeString(s string) string {
type frame struct {
prev string
times int
}
var stack []frame
cur := ""
k := 0
for i := 0; i < len(s); i++ {
c := s[i]
if c >= '0' && c <= '9' {
k = k*10 + int(c-'0')
} else if c == '[' {
stack = append(stack, frame{cur, k})
cur = ""
k = 0
} else if c == ']' {
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
cur = top.prev + strings.Repeat(cur, top.times)
} else {
cur += string(c)
}
}
return cur
}C#Tested in our runner
public class Solution {
public string decodeString(string s) {
var prevs = new Stack<string>();
var counts = new Stack<int>();
string cur = "";
int k = 0;
foreach (char ch in s) {
if (char.IsDigit(ch)) {
k = k * 10 + (ch - '0');
} else if (ch == '[') {
prevs.Push(cur);
counts.Push(k);
cur = "";
k = 0;
} else if (ch == ']') {
string prev = prevs.Pop();
int times = counts.Pop();
cur = prev + string.Concat(Enumerable.Repeat(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 inrfindorlastIndexOf.k = int(ch)in the stack version. It reads only one digit, so10[a]becomes0repeats. Usek = k * 10 + digitfor every digit.- Not resetting
kto 0 after[. The next block inherits the old count, so2[a]bcan repeatbtwice. Reset bothcurandkafter pushing. cur = cur + prevorcur = cur * times + prevwhen 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]returnsa. A count of 1 is valid and must not change the text.100[a]returns 100 lettersa. The count has three digits, so digit accumulation must work for any length.2[ab3[c]]returnsabcccabccc. A letter before a nested block must stay in front of it.abcwith no brackets returnsabc. The brute force loop never runs, and the stack version returnscurdirectly.10[a2[b]]returns 10 copies ofabb. The count10must not be read as1and0.- 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
Related problems
- Simplify Path · same technique: Simulation / Backtracking Helper
- Asteroid Collision · same technique: Simulation / Backtracking Helper
- Reconstruct Itinerary · same technique: Simulation / Backtracking Helper
- Baseball Game · same technique: Simulation / Backtracking Helper
- Crawler Log Folder · same technique: Simulation / Backtracking Helper
- Evaluate Reverse Polish Notation · same pattern: Stack Patterns
- Min Stack · same pattern: Stack Patterns
- Daily Temperatures · same pattern: Stack Patterns
- Car Fleet · same pattern: Stack Patterns
- Valid Parenthesis String · same pattern: Stack Patterns