Decode String — LeetCode 394 Python Solution

MediumStackRecursionString
Problem
#394
Pattern
Stack
Reading time
3 min

The problem

Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.

Example

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

Python solution

Python
class Solution:
    def decodeString(self, s: str) -> str:
        s1, s2 = [], []
        num, res = 0, ''
        for c in s:
            if c.isdigit():
                num = num * 10 + int(c)
            elif c == '[':
                s1.append(num)
                s2.append(res)
                num, res = 0, ''
            elif c == ']':
                res = s2.pop() + res * s1.pop()
            else:
                res += c
        return res

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 394. Decode String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 394. Decode String?
LeetCode 394. Decode String is rated Medium on LeetCode.
What is the time complexity of LeetCode 394. Decode String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 394. Decode String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 394. Decode String cover?
LeetCode 394. Decode String is tagged Stack, Recursion and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview