Decode String

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Decode String

Approach

Track nested context with two stacks: one for repeat counts and one for partial strings. On opening bracket, push current context. On closing bracket, pop and expand the built segment by its repeat count.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Stack (Nested State)

Why It Works

Each bracketed level saves its outer state, so nested expansions resolve inner to outer in LIFO order and rebuild the final decoded string correctly.

Updated Feb 2026