Skip to main content
Back to problems
Leetcode
Medium
Stacks
Strings
Recursion
Google
Meta
Decode String

Decode an encoded string where counts and brackets describe repeated substrings.

Acceptance 0%
Problem Statement

Problem

You are given an encoded string containing lowercase letters, digits, and square brackets. The string uses the format k[encoded_string], where the substring inside the brackets should be repeated k times.

The encoding can be nested, meaning an expanded substring may itself contain more encoded parts.

Return the fully decoded string.

Notes

  • k is always a positive integer.
  • Brackets are always well-formed.
  • Letters outside brackets should remain in the output in the same order.
  • The decoded result may be much larger than the input.

Input Format

  • A single string s.
  • s contains lowercase English letters, digits, and the characters [ and ].
  • The input is a valid encoded expression.

Output Format

  • Return the decoded string after expanding all repetitions and nested groups.

Constraints

  • 1s1051 \le |s| \le 10^5
  • Encoded counts are positive integers.
  • The decoded string length may be large; use a method that builds the result incrementally.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

"aaabcbc"

Explanation

a is repeated 3 times, and bc is repeated 2 times. Concatenate the results: aaa + bcbc = aaabcbc.

Example 2

Input

s = "3[a2[c]]"

Output

"accaccacc"

Explanation

First decode the inner part 2[c] as cc, then expand a2[c] to acc, and finally repeat it 3 times.

Show 1 more example

Example 3

Input

s = "2[abc]3[cd]ef"

Output

"abcabccdcdcdef"

Explanation

Expand each bracketed segment and keep the trailing characters ef unchanged.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.