How to Decode a String with Repeated Brackets in Python

Decodes strings with patterns like '3[a]2[bc]' by using a stack to handle nested and repeated bracket groups.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

25 lines
Python 3.9+
def decode_string(s: str) -> str:
    stack = []
    current_num = 0
    current_str = ""

    for ch in s:
        if ch.isdigit():
            current_num = current_num * 10 + int(ch)
        elif ch == "[":
            stack.append((current_str, current_num))
            current_str = ""
            current_num = 0
        elif ch == "]":
            prev_str, num = stack.pop()
            current_str = prev_str + current_str * num
        else:
            current_str += ch

    return current_str


if __name__ == "__main__":
    test_cases = ["3[a]2[bc]", "2[abc]3[cd]ef", "3[a2[c]]"]
    for case in test_cases:
        print(f"{case} -> {decode_string(case)}")

Output

stdout
3[a]2[bc] -> aaabcbc
2[abc]3[cd]ef -> abcabccdcdcdef
3[a2[c]] -> accaccacc

How it works

The algorithm uses a stack to track the string prefix and the repetition count before each '['. When a digit is encountered, it is accumulated to handle multi-digit numbers. On ']', the algorithm pops the previous string and count, appends the current string repeated the given number of times, and sets it as the new current string. This naturally handles nested brackets because each level is pushed and later popped in LIFO order. The final result is the accumulated string after processing all characters.

Common mistakes

  • Forgetting that numbers can be multi-digit, so accumulate digits until '['
  • Not resetting current_num after a '[' or ']'
  • Popping from an empty stack when the input is malformed
  • Treating digits as part of the string instead of handling them separately

Variations

  1. Use recursion to parse brackets by finding matching ']' and processing inner substrings recursively
  2. Use a regex-based parser to identify bracket groups and repetition counts, though it is less efficient for nested patterns

Real-world use cases

  • Parsing and expanding compressed or encoded configuration strings in data transfer protocols.
  • Decoding serialized pattern strings in educational exercise generators or text expanders.
  • Processing nested command templates in automation scripts where repetition counts define repeat actions.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.