Skip to content

visual walkthrough

Decode String

MediumNested ParsingReported at: GoogleMicrosoftAmazon+11

Nested brackets handled with a stack of (string, count) frames.

Solve on LeetCode

The idea

Brackets can nest, so when a group opens you must remember what you were building and how many times the new group will repeat. A stack of (text so far, repeat count) does that.

On the closing bracket, pop the saved pair, repeat what was just built, and attach it to the saved text.

Complexity

approachtimespace
Stack of (text, count)O(output length)O(depth)

More walkthroughs