ExamAdda Logo

Decode String

Medium

Given an encoded string s, decode it and return the decoded string.

The encoding rule is:

k[encoded_string]

 

where encoded_string inside the square brackets is repeated exactly k times.

You may assume that:

  • The input is always valid.
  • There are no extra spaces.
  • Digits are used only for repetition counts.

Example 1

Input

s = "3[a]2[bc]"

Output

"aaabcbc"

Explanation

3[a] → aaa
2[bc] → bcbc

 

Combining them:

aaabcbc

Example 2

Input

s = "3[a2[c]]"

Output

"accaccacc"

Explanation

First decode:

2[c] → cc

 

So:

a2[c] → acc

 

Then repeat three times:

accaccacc

 

Constraints

1 <= s.length <= 30
s consists of lowercase English letters
digits
and square brackets.
1 <= k <= 300
The encoded string is valid.
The decoded string length will not exceed 10^5.

Hints:

Hint 1

Use a stack to keep track of the strings and repetition counts when encountering [.

Hint 2

When you encounter a digit, build the complete repetition number.

When you encounter ], pop the previous string and repeat the current string the required number of times.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 27, 2026

Last updated

Aug 27, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output