Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Decode String Problem: Mastering Stacks for Nested String Parsing
Apr 29, 2025
442 views
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
1️⃣ Understanding the Problem
Why is this relevant?
👉 It mimics real-world scenarios like:
Rules:
Key Observations:
Identifying the Need for Stacks
Analogy:
Data Structures Needed:
Algorithm Steps:
Let's take the string and see how the algorithm works:
Initialize:
'[': Push currentNumber (3) to countStack. Push currentString ('') to stringStack. Reset currentNumber = 0 and currentString = ''.'[': Push currentNumber (2) to countStack. Push currentString ('a') to stringStack. Reset currentNumber = 0 and currentString = ''.']': Pop countStack (2) Pop stringStack ('a'). currentString = 'a' + 'c'.repeat(2) = 'a' + 'cc' = 'acc'.']': Pop countStack (3) Pop stringStack (''). currentString = '' + 'acc'.repeat(3) = 'accaccacc'.Why Stacks Work:
let currentNum = 0
let currentString = ""
let countStack = []
let stringStack = []
1️⃣ Understanding the Problem
Why is this relevant?
👉 It mimics real-world scenarios like:
Rules:
Key Observations:
Identifying the Need for Stacks
Analogy:
Data Structures Needed:
Algorithm Steps:
Let's take the string and see how the algorithm works:
Initialize:
'[': Push currentNumber (3) to countStack. Push currentString ('') to stringStack. Reset currentNumber = 0 and currentString = ''.'[': Push currentNumber (2) to countStack. Push currentString ('a') to stringStack. Reset currentNumber = 0 and currentString = ''.']': Pop countStack (2) Pop stringStack ('a'). currentString = 'a' + 'c'.repeat(2) = 'a' + 'cc' = 'acc'.']': Pop countStack (3) Pop stringStack (''). currentString = '' + 'acc'.repeat(3) = 'accaccacc'.Why Stacks Work:
let i = 0
for (let char of s) {
if (!isNaN(char)) { // if a number currentNum = currentNum * 10 + parseInt(char) }else if (char === '[') { countStack.push(currentNum) stringStack.push(currentString) currentNum = 0 currentString = "" }else if (char === ']') { let num = countStack.pop() let prevString = stringStack.pop() currentString = prevString + currentString.repeat(num) }else { currentString += char }}
};