← Questions
Decode a string with nested repeat counts
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests stacks, strings and recursion.
An encoded string uses k[...] to mean the bracketed part repeated k times, and brackets may nest. Letters outside brackets appear once. Return the decoded string.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
decode(s: str) -> str— the input is always well formed; counts are positive integers and may have several digits.
Example
"3[a2[c]]" -> "accaccacc"
"2[ab]3[x]" -> "ababxxx"
"xy2[z]w" -> "xyzzw"
"10[a]" -> "aaaaaaaaaa"
Constraints
- The input is short, but nesting can be several levels deep.
- The decoded string can be far longer than the input.
Clarifying questions
- Is the input always valid?
- Can counts have several digits, or be zero?
- Do digits ever appear as literal characters?
- How long can the output get?
What a strong answer covers
- A stack of
(string_so_far, count)frames: push on[, pop and repeat on]; or a recursive parser that returns the decoded part and the index where it stopped. - Reading multi-digit counts.
- Building output with lists and joins rather than repeated string concatenation.
- Cost in terms of output length, which can be exponential in the input length (
9[9[9[a]]]). - Tests: no brackets, deep nesting, adjacent groups, letters after a group.
Follow-ups
- Return only the decoded length without building the string.
- Return the character at position
iof the decoded string when the output is too large to build. - Encode a string into the shortest such form.
Where it's asked
- Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
