Decode String solution explained
Decode String asks you to expand an encoded string where a number followed by a bracketed block means the block is repeated that many times, and blocks can nest, so 2[a3[b]] becomes abbbabbb. The standard one-pass answer uses a stack: at an opening bracket, push the text built so far and the pending count, then start a fresh piece; at a closing bracket, pop them and append the piece repeated count times. A recursive parser that calls itself at each bracket is the equivalent alternative.
By Evin JohnPublished 8 min read
The task, restated
You get an encoded string and must return the decoded one. Ordinary letters stand for themselves. The pattern k[block] stands for block written k times in a row, where k is a positive whole number that may have more than one digit. Blocks may contain letters, other encoded blocks, or both, nested to any depth. The input is always well formed: every count is followed by an opening bracket, brackets are balanced, and digits appear only as counts.
| Encoded | Decoded | What it exercises |
|---|---|---|
| 3[ab]2[c] | abababcc | Two blocks side by side |
| 2[a3[b]] | abbbabbb | A block inside a block |
| x2[yz]w | xyzyzw | Letters before and after a block |
| 12[q] | q repeated twelve times | A count with two digits |
| 2[3[k]j] | kkkjkkkj | Inner block followed by a letter inside the outer block |
| plain | plain | No brackets at all |
Two questions are worth asking. Can a count be 0, or a block be empty? The code below handles both by producing nothing, but say so. And how long can the output get? Each nesting level multiplies, so 9[9[9[9[a]]]] is only 13 characters yet decodes to 6,561. If the interviewer expects huge outputs, the conversation may turn to streaming the result instead of building it.
Do not confuse this with Decode Ways, which counts how many ways a string of digits can be read as letters. That one is dynamic programming; this one is parsing with a stack.
Why it is a popular stack question
Decode String sits one step above bracket matching. Matching only asks whether brackets pair up; here each opening bracket must remember context, namely what had been built so far and how many times to repeat what comes next. That is the same idea as saving a caller's state before a function call, and interviewers use it to see whether you can design the stack entry instead of pushing single characters. Variations you may hear:
- Write the encoder. Given a string, produce the shortest encoding. That is a much harder dynamic programming problem; say so and ask which direction they want.
- Return only the length of the decoded string. Track lengths instead of strings, which avoids building huge outputs.
- Return the k-th character of the decoded string. Compute lengths first, then walk backward with modular arithmetic, without ever building the string.
- Allow uppercase letters or other symbols. Nothing changes as long as they are not digits or brackets.
A slow reference: expand the innermost block
The first closing bracket in the string must close the innermost block, and the last opening bracket before it is its partner. Between them there are only letters. Read the digits just before the opening bracket to get the count, replace the whole k[letters] piece with the letters repeated k times, and repeat until no brackets remain. Each round copies the entire string, which makes this slow on deep inputs, but it is short and obviously correct, so it is a handy oracle when testing the faster version.
def decode_slow(s):
while "]" in s:
close = s.index("]")
open_at = s.rindex("[", 0, close)
start = open_at
while start > 0 and "0" <= s[start - 1] <= "9":
start -= 1
times = int(s[start:open_at])
s = s[:start] + s[open_at + 1:close] * times + s[close + 1:]
return sDesigning the stack entry
Scan left to right while keeping two things: current, the decoded text of the block you are inside, and count, the number being read digit by digit. A letter is appended to current. A digit extends count. An opening bracket means a new inner block starts, so push the pair (current, count) and reset both. A closing bracket means the inner block is finished: pop (before, times), and the new current is before followed by the inner text repeated times. When the scan ends, current holds the answer, because the outermost level never had a bracket of its own.
Optimal approach: one pass with a stack of pairs
def decode(s):
stack = [] # (pieces before the bracket, repeat count)
current, count = [], 0
for ch in s:
if "0" <= ch <= "9":
count = count * 10 + int(ch)
elif ch == "[":
stack.append((current, count))
current, count = [], 0
elif ch == "]":
before, times = stack.pop()
before.append("".join(current) * times)
current = before
else:
current.append(ch)
return "".join(current)function decodeString(s) {
const stack = [];
let current = "";
let count = 0;
for (const ch of s) {
if (ch >= "0" && ch <= "9") {
count = count * 10 + (ch.charCodeAt(0) - 48);
} else if (ch === "[") {
stack.push([current, count]);
current = "";
count = 0;
} else if (ch === "]") {
const [before, times] = stack.pop();
current = before + current.repeat(times);
} else {
current += ch;
}
}
return current;
}The Python version collects pieces in a list and joins them once per closing bracket, which avoids building a new string on every letter. The JavaScript version uses plain concatenation, which engines handle well for strings of this kind. Either choice is fine to defend in an interview; what matters is that the count is reset to 0 after it is pushed, so the next block starts reading a fresh number.
Trace: 2[a3[b]]
| Character | Action | current | count | Stack |
|---|---|---|---|---|
| 2 | read digit | [] | 2 | [] |
| [ | push and reset | [] | 0 | [([], 2)] |
| a | append letter | [a] | 0 | [([], 2)] |
| 3 | read digit | [a] | 3 | [([], 2)] |
| [ | push and reset | [] | 0 | [([], 2), ([a], 3)] |
| b | append letter | [b] | 0 | same |
| ] | pop ([a], 3), append bbb | [a, bbb] | 0 | [([], 2)] |
| ] | pop ([], 2), append abbbabbb | [abbbabbb] | 0 | [] |
The recursive alternative
Some interviewers prefer recursion because it mirrors the grammar. A helper reads from a shared position: it collects letters, and when it meets a count it reads the digits, skips the opening bracket, calls itself to decode the inside, then repeats the returned text. When it meets a closing bracket it skips it and returns. The call stack plays the role of the explicit stack. The cost is the same; the risk is very deep nesting, which can exceed the default recursion limit in Python at around a thousand levels.
Time and space
| Approach | Time | Extra space |
|---|---|---|
| Innermost-first rewriting | One full copy of the string per bracket pair, so roughly O(n times L) in bad cases | O(L) |
| Stack of pairs | O(n) plus the size of every intermediate string built, between L and about d times L | O(L) for the result plus O(d) stack entries |
| Recursive parser | Same as the stack version | O(L) plus O(d) call frames |
| Length only (follow-up) | O(n) | O(d) |
Many write-ups quote a bound in terms of the largest count raised to the nesting depth. That is the worst-case output length for a given input size, and it is a useful thing to say aloud: the output, not the input, is what drives the cost.
Edge cases
- No brackets: the input comes back unchanged.
- Counts of two or more digits, such as 12[q] or 100[ab].
- Letters after the last closing bracket of a nested block, as in 2[3[k]j].
- A count of 0 or an empty block, if the interviewer allows them: both produce an empty piece and the code handles them.
- Very large outputs: ask whether to build the string at all, or to return its length or a single character instead.
Mistakes to avoid
- Reading a single digit as the whole count, which decodes 12[q] as 1 then 2[q].
- Forgetting to reset count after pushing it.
- Pushing only the count, then losing the text that came before the bracket.
- Repeating the text before the bracket along with the block, as in turning x2[y] into xyxy instead of xyy.
- Building strings with repeated concatenation inside a deep loop in a language where that is quadratic, without mentioning it.
- Assuming the answer fits comfortably in memory without asking about output size.
How to explain it out loud
Fictional example
- Candidate
- I'll scan once and keep the text of the block I'm in plus the count I'm reading. Letters append, digits build the count, so 12 reads as twelve.
- Candidate
- On an opening bracket I push the text so far and the count, then reset both. On a closing bracket I pop them and set the text to what came before plus the inner text repeated.
- Candidate
- Cost is driven by how big the strings get, so before I code it: is there a limit on the decoded length? If not, we might want the length or a single character instead of the full string.
Related problems
Basic Calculator uses an identical save-and-restore stack, with a running total and a sign in place of text and a count. Union-Find is a change of scene, but it rewards the same habit of saying what each stored value means before writing the loop. Valid Parentheses is the simpler bracket problem underneath both.
How Natively fits into practice
When you drill parsing problems on a Mac or Windows PC, Natively can pick up the problem from the page through its Chrome extension, or from a screenshot, and write an approach with code to check against yours. Sessions are saved with their transcripts and can be exported as Markdown or PDF, so you can keep a log of the explanations that went well and the ones that did not. More on the AI interview assistant page.
Questions people ask
How do you solve Decode String?
Scan once, keeping the text of the current block and the count being read. At an opening bracket push both and reset; at a closing bracket pop them and set the text to the saved text plus the inner text repeated.
How do you handle counts with more than one digit?
Build the count digit by digit with count = count * 10 + digit, and reset it to 0 after pushing it at an opening bracket.
What is the time complexity of Decode String?
It is driven by the output size rather than the input size. The stack version spends time proportional to the strings it builds, which is at least the output length and grows with nesting depth.
Can Decode String be solved recursively?
Yes. A helper reads letters, and when it meets a count it reads the digits, decodes the bracketed part with a recursive call, and repeats the result. The call stack replaces the explicit stack.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
