Skip to problem
←

Decode String

Medium 0 attempts

You're given an encoded string such as "3[a2[c]]" and need to expand it back out. The rule k[encoded_string] means that encoded_string should appear repeated k times in a row, and these rules can be nested inside one another.

Function contract

Implement decodeString(s), where s is a valid encoding using lowercase letters, positive integer repeat counts, and square brackets.

Output: The fully expanded string, preserving the order of literal text and repeated groups.

Example 1

Input
s = "3[a]2[bc]"
Output
"aaabcbc"

Example 2

Input
s = "3[a2[c]]"
Output
"accaccacc"

Explanation: First decode 2[c] as cc, then repeat acc three times.

Constraints
  • 1 <= s.length <= 30
  • Input encoding is valid; repeat counts lie in [1,300].
  • The decoded output has at most 10^5 characters.
  • Digits appear only as repeat counts immediately before [. Literal text consists of lowercase English letters.

Stack-Based Parsing

Use stacks to track multiplier and current string at each nesting level.

javascript
function decodeString(s) {
  const numStack = [], strStack = [];
  let curr = '', num = 0;
  for (const c of s) {
    if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
    else if (c === '[') { numStack.push(num); strStack.push(curr); num = 0; curr = ''; }
    else if (c === ']') { curr = strStack.pop() + curr.repeat(numStack.pop()); }
    else curr += c;
  }
  return curr;
}

Time: O(n + W), where W is the total number of characters copied while building intermediate strings. A conservative worst-case bound is O(n × L) for encoded length n and decoded length L; nested groups may copy the same expanded text more than once. Space: O(n + L) for the stacks and live strings, including output.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript