1. Decode the String
The problem can be found at the following link: Question Link
Problem Description
Given an encoded string s, the task is to decode it.
The encoding rule is:
k[encoded_string], where the encoded string inside the square brackets is repeated exactlyktimes.Note:
kis guaranteed to be a positive integer.
Examples
Example 1:
Input:
s = "1[b]"
Output:
b
Explanation:
The string "b" is present only once.
Example 2:
Input:
s = "3[b2[ca]]"
Output:
bcacabcacabcaca
Explanation:
First,
2[ca]expands tocacaThen,
3[bcaca]expands tobcacabcacabcacawhich is the final output.
Constraints:
$(1 \leq |s| \leq 10^5)$
My Approach
Stack-Based Iterative Approach (O(N) Time, O(N) Space)
The goal is to parse and decode nested patterns like k[encoded_string] using a stack-based simulation.
Algorithm Steps:
Use two stacks:
One for tracking the string built so far.
One for tracking the repetition counts (
k).
Iterate over the string:
If you see a digit, accumulate it into
k.If you see
[, push the current string and currentkto the stacks, then reset them.If you see
], pop the previous string andk, and append the current string repeatedktimes.Otherwise, append the character to the current string.
The final decoded string will be the result.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(N), since each character is processed at most twice (once when pushed, once when popped).
Expected Auxiliary Space Complexity: O(N), as the worst case (deeply nested or large repeated sections) can push every character onto the stack.
Code (C++)
β‘ Alternative Approaches
2οΈβ£ Using deque Instead of Stack (O(N) Time, O(N) Space)
deque Instead of Stack (O(N) Time, O(N) Space)This approach uses deque instead of stack for better performance on larger inputs.
πΉ Pros: Faster due to deque's optimized access.
πΉ Cons: Similar complexity but slight memory overhead.
3οΈβ£ Recursive Approach (O(N) Time, O(N) Space)
This recursive solution simulates decoding via DFS.
πΉ Pros: Uses recursion to break down the problem naturally. πΉ Cons: Higher memory usage due to recursive stack frames.
π Comparison of Approaches
Approach
β±οΈ Time Complexity
ποΈ Space Complexity
β Pros
β οΈ Cons
Stack-Based Iterative
π’ O(N)
π’ O(N)
Simple and fast
None
Deque-Based Iterative
π’ O(N)
π‘ O(N)
Slightly faster for large data
Slightly more complex
Recursive DFS
π’ O(N)
π΄ O(N)
Elegant for nested parsing
Stack overflow risk
π‘ Best Choice?
β For practical use: Stack-based iterative (O(N) time, O(N) space) is the best balance.
β For highly nested strings: Recursive DFS can be more intuitive.
β For micro-optimizations: Deque-based version is worth considering.
Code (Java)
Code (Python)
Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated