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
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Medium

0

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
Stack
Parsing
Recursion
String building
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported