Great question! Leetcode 394. Decode String is a classic problem that involves parsing and decoding strings with nested patterns like "3[a2[c]]" → "accaccacc".
🔍 Problem Summary:
Given an encoded string , return its decoded version. The encoding rule is:
k[encoded_string] , where the encoded_string inside the square brackets is repeated exactly k times .
You can assume the input string is always valid (no malformed brackets, etc.).
📌 Examples:
plaintext Copy code
Input: "3[a]2[bc]"
Output: "aaabcbc"
Input: "3[a2[c]]"
Output: "accaccacc"
Input: "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
✅ Optimal Approach
This problem involves decoding nested structures , which is a strong hint for two approaches:
Stack-based solution 👍 (iterative)
Recursive solution (DFS-style parsing) 👍
1️⃣ Stack-Based Approach (Iterative ✅ Preferred for Iterative Languages like Go)
This is considered the most efficient and clear approach, especially in Go , which lacks built-in recursion optimizations like tail-call.
Key Idea:
Use two stacks :
One for numbers (k multipliers)
One for strings (what’s built so far before the [ ])
Pseudocode:
Iterate over characters s[i] from the input:
If it's a digit , accumulate the full number (handles multi-digit numbers like 100[abc])
If it's a [ , push currentNum and currentString onto the stacks. Then reset them.
If it's a ] , pop the last string & count from the stacks → build the decoded string:
lastString + repeat(currentString, count)
If it's a letter , append to currentString
✅ Go Implementation:
go Copy code
func decodeString(s string) string {
numStack := []int{}
strStack := []string{}
currStr := ""
currNum := 0
for i := 0; i < len(s); i++ {
ch := s[i]
if ch >= '0' && ch <= '9' {
// Parse full number
currNum = currNum*10 + int(ch-'0')
} else if ch == '[' {
// Push state to stacks
numStack = append(numStack, currNum)
strStack = append(strStack, currStr)
// Reset for new scope
currNum = 0
currStr = ""
} else if ch == ']' {
// Pop count and previous string
repeatCount := numStack[len(numStack)-1]
numStack = numStack[:len(numStack)-1]
prevStr := strStack[len(strStack)-1]
strStack = strStack[:len(strStack)-1]
// Decode and append
decoded := ""
for j := 0; j < repeatCount; j++ {
decoded += currStr
}
currStr = prevStr + decoded
} else {
// Regular character
currStr += string(ch)
}
}
return currStr
}
2️⃣ Recursive Approach (Elegant but Requires Helper Function)
This simulates the parsing as a depth-first traversal — each [...] block is a recursive call.
✅ Go Recursive Version:
go Copy code
func decodeString(s string) string {
i := 0
return dfs(s, &i)
}
func dfs(s string, i *int) string {
res := ""
num := 0
for *i < len(s) {
ch := s[*i]
if ch >= '0' && ch <= '9' {
num = num*10 + int(ch-'0')
*i++
} else if ch == '[' {
*i++
sub := dfs(s, i) // recursive decode
for j := 0; j < num; j++ {
res += sub
}
num = 0
} else if ch == ']' {
*i++
return res
} else {
res += string(ch)
*i++
}
}
return res
}
🧠 Recursive vs Stack Comparison:
Criteria Stack-Based Recursive Performance ✅ Optimal ✅ Optimal Readability ✅ Clear in Go ✅ Elegant (DFS) Tail-recursion ❌ No in Go ❌ Might cause stack overflow on deep nesting Complexity O(n) time & space O(n) time & space
✅ Final Verdict: Use Stack-Based Approach in Go
✔️ It avoids recursion depth issues
✔️ It’s clear, efficient, and directly follows the "decode while parsing" logic
✔️ It can handle large and deeply nested inputs safely
🧠 Time and Space Complexity
Time: O(n), where n is length of string
→ Each character is processed once.
Space: O(n) for stacks (in worst case, all characters are in stacks)
Let me know if you'd like a visual explanation or step-by-step debug trace!