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.
Python code
25 linesdef 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
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
- Use recursion to parse brackets by finding matching ']' and processing inner substrings recursively
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.