Expand Nested Repeat Patterns Like 3[a2[bc]]
Last updated: November 29, 2026
Quick Overview
Given an encoded string where k[s] means s repeated k times and brackets can nest, return the fully expanded string.
Microsoft
November 29, 20260
0
0 solved
Given an encoded string where k[s] means s repeated k times and brackets can nest, return the fully expanded string.
A parsing question in the style of Microsoft phone screens, close to the tokenizing work done in compilers, Excel formula parsing, and template engines. The interviewer checks that you choose a stack, parse multi-digit counts, and keep string building linear rather than quadratic.
What the Interviewer Expects
- Recognizes nested structure and uses an explicit stack or recursion
- Parses multi-digit repeat counts
- Builds strings with lists to avoid repeated concatenation in loops
- Validates unbalanced brackets
- Discusses output size blowup and streaming
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- The expanded output could be gigabytes: how would you return the character at index i without expanding?
- Write the encoder that produces the shortest encoding.
- How would you solve it recursively, and what are the stack depth risks?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input contains lowercase letters, digits, and brackets. Digits always precede [. Counts can be multi-digit or zero. Output is the expanded string. Malformed input should raise....
High-Level Design
Each [ opens a new context. When I see it, I push the text built so far plus the pending count, then start fresh. When I see ], the current buffer is the body of the innermost repeat: pop the save...