Skip to content
BytePatterns

Decode Nested Repeats

MediumStacks & Queues#stack#string-parsing~30m

Problem

An encoded text uses the form k[segment], meaning the segment is repeated k times. The repeat count k is a positive whole number that may have several digits, and a segment may itself contain further encoded segments. Expand the encoding and return the plain text.

Examples

Input:  text = "3[a]2[bc]"
Output: "aaabcbc"
Input:  text = "2[ab3[c]]"
Output: "abcccabccc"
Why:    the inner segment expands first, then the outer one repeats the result
Input:  text = "xyz"
Output: "xyz"
Why:    edge case, text with no encoding passes through unchanged

Hints

0 / 3

Stuck on the idea rather than the code? Stack Basics covers it.