Mediumstack-parsing
Decode String
Problem (restated)
Encoded string like 3[a2[c]] → accaccacc. Digits mean repeat count; brackets nest.
Intuition
Two stacks (or one stack of frames): counts and string builders. On ] pop and repeat.
Approaches
Stack parse
Tested onlyTime O(n · output)Space O(output)
Idea. On digit accumulate k; on [ push frame; on letter append; on ] repeat and merge.
Walkthrough. 3[a]2[bc] → aaabcbc; 3[a2[c]] → accaccacc.
Trade-offs. Recursive descent is fine; stack mirrors call frames.
Solution
export function decodeString(s: string): string {
const countSt: number[] = [];
const strSt: string[] = [];
let cur = "";
let k = 0;
for (const ch of s) {
if (ch >= "0" && ch <= "9") k = k * 10 + (ch.charCodeAt(0) - 48);
else if (ch === "[") {
countSt.push(k);
strSt.push(cur);
cur = "";
k = 0;
} else if (ch === "]") {
const times = countSt.pop()!;
const prev = strSt.pop()!;
cur = prev + cur.repeat(times);
} else cur += ch;
}
return cur;
}
export function decodeString(s: string): string {
const countSt: number[] = [];
const strSt: string[] = [];
let cur = "";
let k = 0;
for (const ch of s) {
if (ch >= "0" && ch <= "9") k = k * 10 + (ch.charCodeAt(0) - 48);
else if (ch === "[") {
countSt.push(k);
strSt.push(cur);
cur = "";
k = 0;
} else if (ch === "]") {
const times = countSt.pop()!;
const prev = strSt.pop()!;
cur = prev + cur.repeat(times);
} else cur += ch;
}
return cur;
}
Template connection
Stack-parsing nested structures.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?