Expand a Run-Encoded Gift Wrap Pattern With Nested Repeats

Last updated: November 29, 2026

Quick Overview

A gift wrap printer receives patterns like `2[ab3[c]]x` meaning repeat the bracketed text the given number of times. Return the fully expanded string; counts can have multiple digits and brackets can nest.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


A gift wrap printer receives patterns like `2[ab3[c]]x` meaning repeat the bracketed text the given number of times. Return the fully expanded string; counts can have multiple digits and brackets can nest.

A technical-screen question in Amazon's style, framed as a compact encoding sent to packaging printers in fulfillment centers. The interviewer looks for a clean stack-based parser, multi-digit count handling, and a reasoned answer about output size limits.

What the Interviewer Expects
  • Handles multi-digit counts like 12[a]
  • Uses a stack (or recursion) to handle nesting
  • Builds strings with lists to avoid quadratic concatenation
  • States that output size can be exponential in input size
  • Traces a nested example correctly
Key Topics to Cover
string parsing
stack
recursion
encoding
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
  • How would you return only the k-th character without expanding the whole string?
  • How do you reject malformed input like 3[a or ]?
  • What if a count can be zero?
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

Letters, digits, and brackets; a number always precedes [. Return the expansion. Ask whether input is guaranteed well formed and whether there is a cap on output length, since 9[9[9[a]]] already p...

High-Level Design

Keep a buffer cur for the string being built at the current nesting level and an accumulator num for a count in progress. On [, push the outer buffer and the count, then start fresh. On ], pop...


Submit Your Answer
Markdown supported