Decode String with Stack and String Manipulation

🚀 50 Important Coding Questions – Question 46/50 🔹 Decode String | LeetCode A classic Stack + String manipulation problem involving nested encoding patterns. 📌 Problem Statement Given an encoded string s, decode it using the rule: k[encoded_string] → repeat encoded_string k times The encoding may be nested. Example: Input s = "3[a2[c]]" Output "accaccacc" Explanation: a2[c] -> acc 3[acc] -> accaccacc 💡 Approach We use a stack to handle nested patterns. Steps: 1️⃣ Traverse the string 2️⃣ Push characters until ] is found 3️⃣ When ] appears: • Pop characters until [ → get substring • Extract the number (k) • Repeat the substring k times • Push back into stack 4️⃣ Continue until string ends 5️⃣ Build final result from stack ⏱ Time Complexity: O(n * k) (due to repeated strings) 📦 Space Complexity: O(n) 📌 LeetCode Result ✔ Accepted ⚡ Efficient stack-based decoding 🧠 Concepts Strengthened ✔ Stack for nested structures ✔ String parsing ✔ Handling multi-digit numbers ✔ Recursion-like behavior using stack 📍 Question 46 of 50 in my “50 Important Coding Questions” series. Only 4 problems left — final stretch! 💯🔥 👉 Question 47 coming next! #DSA #LeetCode #Stack #Strings #CodingInterview #ProblemSolving #CPlusPlus #TechJourney

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories