Decode String
Problem Statement
You are given an encoded string s. The rule is k[text]: the part inside the square brackets is written out k times in a row. k is a positive whole number and can have more than one digit.
Groups can be nested inside each other, like 3[a2[c]]. Return the fully decoded string.
You can assume the input is always well formed: brackets match, there are no extra spaces, digits only appear as repeat counts (never as text), and every [ comes right after its count.
An encoded string s of lowercase letters, digits and square brackets.
The decoded string.
"a" three times, then "bc" two times.
The inner 2[c] becomes "cc", so the group is "acc". Writing it 3 times gives "accaccacc".
"abc" twice, "cd" three times, then the plain letters "ef".
- • 1 ≤ s.length ≤ 30
- • s has lowercase letters, digits and '[' ']'
- • Every repeat count k is in [1, 300]
- • The decoded string is at most 10^5 characters long
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Find the first ']', expand its k[...] in place, rebuild the string, repeat
On '[' push (k, cur) and reset; on ']' pop and cur = prev + cur × k
Find the first ]. The last [ before it opens a group with only letters inside, so it can be expanded right now: read the count before the [, write the inside k times, and rebuild the string with that group replaced. Repeat until no brackets are left.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Stack translate into production architectures and low-level memory mechanics.