↓Skip to main content
  1. LeetCode/

LeetCode 394: Decode String

·2 mins· ·
LeetCode Medium Stack String Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-10-08

  • Submissions: Wrong Answer → Accepted

Approach
#

k[encoded] can nest, e.g. 3[a2[c]]. This is a classic stack problem:

  • On [: push the string accumulated so far and this bracket’s count, then start accumulating the inside.
  • On ]: the inside is complete; pop the outer string and count, and form outer + inside * count.

My First Attempt: assuming a single-digit count
#

stack.pop()                       # pop "["
repeat_time = int(stack.pop())    # only one character taken as the count

The first version pushed every character and popped back to [ on ]. The count was popped as a single character, so 10[a] was treated as 0[a]. The second version popped while the top was a digit, and passed.

Solution
#

class Solution:
    def decodeString(self, s: str) -> str:
        stack = []
        cur, num = "", 0
        for ch in s:
            if ch.isdigit():
                num = num * 10 + int(ch)
            elif ch == "[":
                stack.append((cur, num))
                cur, num = "", 0
            elif ch == "]":
                prev, k = stack.pop()
                cur = prev + cur * k
            else:
                cur += ch
        return cur

The stack holds “the outer string and count” rather than individual characters, so ] never has to search back for [ or rebuild strings character by character.

Complexity
#

Time O(output length), space O(output length).

Mistakes to Avoid
#

  • Assuming the count has one digit.
  • Pushing every character and rebuilding on ]: it passes, but it is slower and more error-prone.

Interview Explanation
#

I handle nested brackets with a stack: digits accumulate into the count (which may have several digits), [ pushes the current string and count and starts fresh, and ] pops the outer string and count and appends this level repeated that many times. The final accumulated string is the answer, in time proportional to the output length.

Related

LeetCode 3703: Remove K-Balanced Substrings
·2 mins
LeetCode Medium Stack String Simulation
LeetCode 3703 note: repeated replace is O(n^2); a stack of (character, run length) removes k ( plus k ) as soon as they line up
LeetCode 402: Remove K Digits
·2 mins
LeetCode Medium String Stack Greedy Monotonic-Stack
LeetCode 402 note: a monotonically increasing stack; while deletions remain, pop any top larger than the current digit, then strip leading zeros
LeetCode 227: Basic Calculator II
·2 mins
LeetCode Medium Math String Stack
LeetCode 227 note: read whole numbers, and at each operator apply the previous one: + and - push the number (negated for -), * and / combine with the top
LeetCode 143: Reorder List
·2 mins
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 note: find the middle, reverse the second half, and merge the two alternately, cutting the first half’s tail
LeetCode 71: Simplify Path
·2 mins
LeetCode Medium String Stack
LeetCode 71 note: split on /, skip empty pieces and ., pop on .. (never above root), push other names, and join with /
LeetCode 2487: Remove Nodes From Linked List
·1 min
LeetCode Medium Linked-List Stack Recursion Monotonic-Stack
LeetCode 2487 note: the kept nodes are non-increasing left to right; keep a monotonic stack, pop anything smaller than the new node, then link what remains