πDay 9. 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.
π Example Walkthrough:
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.
π Solution Code
Code (C++)
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