DSA Stacks

Decode String

Stacks of (count, prefix); on each `]` apply the multiplication and concatenate back to the outer prefix.

Medium
Time O(maxK * n) Space O(n)
LeetCode
4 min read
stack parsing string

Problem#

Decode a string formatted as k[encoded] where k is a positive integer and encoded is a string. Repeat encoded exactly k times. Brackets can nest.

Examples#

  • "3[a]2[bc]""aaabcbc"
  • "3[a2[c]]""accaccacc"
  • "2[abc]3[cd]ef""abcabccdcdcdef"

Constraints#

  • 1 <= s.length <= 30, s contains only lowercase letters, digits, and [ ].

Approach#

Two stacks: one for prior counts, one for prior prefixes. Parse digits to form a multi-digit count. On [, push (currentCount, currentPrefix) and reset. On ], repeat the current prefix by the popped count and append to the popped prefix. Letters append to the current prefix.

Solution#

Decode String
class Solution {
public:
string decodeString(string s) {
stack<int> counts;
stack<string> prefixes;
string cur;
int k = 0;
for (char c : s) {
if (isdigit(c)) {
k = k * 10 + (c - '0');
} else if (c == '[') {
counts.push(k);
prefixes.push(cur);
k = 0;
cur.clear();
} else if (c == ']') {
int rep = counts.top(); counts.pop();
string prev = prefixes.top(); prefixes.pop();
while (rep--) prev += cur;
cur = prev;
} else {
cur.push_back(c);
}
}
return cur;
}
};

Editorial#

The two-stack design keeps the half-built outer string safe while we focus on the inner sub-expression. Numbers can be multi-digit, so we accumulate k across digits. The total time is bounded by the length of the expanded output.

Complexity#

  • Time: O(maxK * n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.