Skip to content
DSA Patterns
Menu
Language
Stack ParsingLC #3945 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time 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

A [ pushes the current count and the prefix built so far, then both reset. A ] repeats the current piece k times and appends it to the popped prefix.

Reflection

  • The count can be several digits: 12[a]. On [, push the repeat count and the string built so far.
  • ] pastes the inner string k times onto the outer one. Nested form: 3[a2[c]].
  • k = 0 produces an empty string. Letters with no count are plain text. The stack should be empty at the end.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Decode 3[a2[c]]. Digits are a repeat count; [ pushes a frame; ] pops and repeats.

3
0
[
1
a
2
2
3
[
4
c
5
]
6
]
7
stack
∅
Key:CurrentActive rangeMatchSettled