Community Problem

Decode String

Difficulty: Medium

Expand a run-length-encoded string with arbitrary nesting using two parallel stacks (counts and string fragments).

Decode String

Expand a run-length-encoded string with arbitrary nesting using two parallel stacks (counts and string fragments).

MEDIUM
Free
stack
strings
recursion

By CodeSnatch

April 5, 2026

·

Updated May 18, 2026

667 views

15

4.6 (12)

This came up on a Tier-1 onsite the week I was prepping for my staff transition, and the misstep I see candidates make is reaching for regex and getting buried by the nested case. The two-stack pattern is the canonical solve and is the same shape that powers basic-calculator and nested-list problems.

Decode String

Given an encoded string s, return its decoded form. The encoding rule is k[encoded_string], where encoded_string inside the brackets is repeated exactly k times. k is a positive integer (one or more digits). The input is guaranteed to be a well-formed encoded string with brackets balanced and k always immediately followed by '['. There are no extra spaces. The encoded string may contain digits inside encoded_string only as part of nested counts (e.g. "3[a2[c]]"), never as raw payload.

Examples

Example 1:

  • Input: s = "3[a]2[bc]"
  • Output: "aaabcbc"
  • Explanation: "3[a]" becomes "aaa", "2[bc]" becomes "bcbc", concatenated.

Example 2:

  • Input: s = "3[a2[c]]"
  • Output: "accaccacc"
  • Explanation: Inner "2[c]" is "cc". Then "3[acc]" is "accaccacc".

Example 3:

  • Input: s = "2[abc]3[cd]ef"
  • Output: "abcabccdcdcdef"
  • Explanation: "abcabc" plus "cdcdcd" plus literal "ef".

Example 4:

  • Input: s = "abc"
  • Output: "abc"
  • Explanation: No brackets, the string is its own decoding.

Constraints

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, '[', and ']'.
  • s is guaranteed to be a valid input that produces a string of length at most 10^4.
  • The integer k satisfies 1 <= k <= 300.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems