The 394. Decode String problem is a classic algorithmic challenge that involves decoding a string with nested patterns of the form k[encoded_string]. The optimal approach depends on how you manage the nested structure and repetition of substrings. Both stacks and recursion are valid approaches, but the choice depends on your preference for implementation style and readability.
Problem Recap:
Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. The input string may contain multiple nested encoded substrings.
Example:
Input: "3[a2[c]]"
Output: "accaccacc"
Approaches:
1. Using a Stack
This is a widely used and efficient approach. A stack is particularly well-suited for problems involving nested structures because it allows you to process elements in a last-in-first-out (LIFO) manner.
Steps:
- Use two stacks:
- One for numbers (
countStack) to store the repetition counts.
- Another for strings (
stringStack) to store the current decoded string before encountering a [.
- Traverse the input string character by character:
- If the character is a digit, parse the number (it could be more than one digit).
- If the character is
[, push the current number onto countStack and the current string onto stringStack, then reset them.
- If the character is
], pop from both stacks, repeat the current string by the popped count, and append it to the previous string.
- If the character is a letter, append it to the current string.
Code Implementation:
def decodeString(s: str) -> str:
countStack = []
stringStack = []
currentString = ""
currentNumber = 0
for char in s:
if char.isdigit():
currentNumber = currentNumber * 10 + int(char) # Handle multi-digit numbers
elif char == '[':
# Push the current state onto the stacks
countStack.append(currentNumber)
stringStack.append(currentString)
currentString = ""
currentNumber = 0
elif char == ']':
# Pop from stacks and decode
num = countStack.pop()
prevString = stringStack.pop()
currentString = prevString + currentString * num
else:
currentString += char
return currentString
Complexity:
- Time Complexity: O(n), where n is the length of the decoded string. Each character is processed once.
- Space Complexity: O(n), due to the stacks storing intermediate results.
2. Using Recursion
Recursion can also solve this problem elegantly by treating each [encoded_string] as a subproblem. This approach is intuitive for problems with nested structures.
Steps:
- Define a helper function that processes the string starting from a given index.
- When encountering a digit, recursively decode the substring inside the brackets.
- Return the decoded string and the index where the current subproblem ends.
Code Implementation:
def decodeString(s: str) -> str:
def helper(index):
result = ""
num = 0
while index < len(s):
char = s[index]
if char.isdigit():
num = num * 10 + int(char) # Handle multi-digit numbers
elif char == '[':
# Recursively decode the substring inside the brackets
index, decodedString = helper(index + 1)
result += decodedString * num
num = 0
elif char == ']':
# End of the current subproblem
return index, result
else:
result += char
index += 1
return result
return helper(0)
Complexity:
- Time Complexity: O(n), where n is the length of the decoded string. Each character is processed once.
- Space Complexity: O(n), due to the recursion stack, which can grow proportional to the depth of nesting.
Comparison of Approaches:
| Aspect | Stack-Based Approach | Recursive Approach |
|---|
| Readability | Easier to follow for most people. | More intuitive for nested problems. |
| Implementation | Iterative, avoids recursion depth. | Recursive, relies on call stack. |
| Performance | Slightly faster in practice. | May hit recursion limits for deep nesting. |
| Space Usage | Uses explicit stacks. | Implicitly uses the call stack. |
Optimal Approach:
For most cases, the stack-based approach is preferred because:
- It avoids potential recursion depth issues for deeply nested inputs.
- It is slightly more efficient in practice since it avoids the overhead of recursive calls.
- It is easier to debug and reason about.
However, if you find recursion more natural or are solving the problem in a language where recursion is idiomatic (e.g., functional programming languages), the recursive approach is equally valid.
Final Recommendation:
Use the stack-based approach unless you have a specific reason to prefer recursion. Here's the final version of the stack-based solution for clarity:
def decodeString(s: str) -> str:
countStack = []
stringStack = []
currentString = ""
currentNumber = 0
for char in s:
if char.isdigit():
currentNumber = currentNumber * 10 + int(char)
elif char == '[':
countStack.append(currentNumber)
stringStack.append(currentString)
currentString = ""
currentNumber = 0
elif char == ']':
num = countStack.pop()
prevString = stringStack.pop()
currentString = prevString + currentString * num
else:
currentString += char
return currentString
This solution is efficient, clear, and handles all edge cases like multi-digit numbers and deeply nested structures.