Code Logo

Decode String

Published at23 Jul 2026
Medium 0 views
Like0

You are given an encoded string following the pattern k[encoded_string], where k is a positive integer indicating how many times the content inside the brackets should be repeated. The brackets can be nested, meaning you must decode the innermost brackets first.

Two stacks provide a clean solution: one stack for repeat counts and one stack for partial results. When you encounter a number, build the full count. When you encounter [, push the current count and current decoded string onto their stacks, then reset both. When you encounter ], pop the count and previous string, repeat the current decoded string count times, and append it to the previous string.

For example, "3[a]2[bc]""aaabcbc". "3[a2[c]]" → inner 2[c] becomes "cc", then 3[acc]"accaccacc".

Example Input & Output

Example 1
Input
3[a2[c]]
Output
accaccacc
Explanation

Inner 2[c] = cc. Outer 3[acc] = accaccacc.

Example 2
Input
2[abc]3[cd]ef
Output
abcabccdcdcdef
Explanation

2[abc]=abcabc, 3[cd]=cdcdcd, then +ef.

Example 3
Input
3[a]2[bc]
Output
aaabcbc
Explanation

3[a] = aaa, 2[bc] = bcbc. Combined: aaabcbc.

Example 4
Input
abc3[cd]xyz
Output
abccdcdcdxyz
Explanation

3[cd]=cdcdcd inserted between abc and xyz.

Algorithm Flow

Recommendation Algorithm Flow for Decode String
Recommendation Algorithm Flow for Decode String

Solution Approach

Use two stacks: countStack and resultStack. Iterate through each character. If it's a digit, build the full number. If it's [, push the current count and current result, then reset both. If it's ], pop count and previous result, repeat the current result count times, and append to previous. Otherwise, it's a letter, append to current result.

function solution(s) {
  var countStack = []
  var resultStack = []
  var result = ''
  var i = 0
  while (i < s.length) {
    if (s[i] >= '0' && s[i] <= '9') {
      var num = 0
      while (i < s.length && s[i] >= '0' && s[i] <= '9') {
        num = num * 10 + Number(s[i])
        i++
      }
      countStack.push(num)
    } else if (s[i] === '[') {
      resultStack.push(result)
      result = ''
      i++
    } else if (s[i] === ']') {
      var repeat = countStack.pop()
      var temp = resultStack.pop()
      for (var j = 0; j < repeat; j++) temp += result
      result = temp
      i++
    } else {
      result += s[i]
      i++
    }
  }
  return result
}

Time complexity is O(n * k) where k is the max repeat count. Space complexity is O(n) for the stacks.

Best Answers

java
import java.util.*;
class Solution {
    public String solution(String s) {
        Stack<Integer> countStack = new Stack<>();
        Stack<String> resultStack = new Stack<>();
        String result = "";
        int i = 0;
        while (i < s.length()) {
            char ch = s.charAt(i);
            if (ch >= '0' && ch <= '9') {
                int num = 0;
                while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                    num = num * 10 + (s.charAt(i) - '0'); i++;
                }
                countStack.push(num);
            } else if (ch == '[') { resultStack.push(result); result = ""; i++; }
            else if (ch == ']') {
                int repeat = countStack.pop();
                String temp = resultStack.pop();
                for (int j = 0; j < repeat; j++) temp += result;
                result = temp; i++;
            } else { result += ch; i++; }
        }
        return result;
    }
}