Monitoring~25 min2s · 256 MBtarget O(n + output) time, O(n + output) spaceclassic twin: lc-394stacks
A monitoring system stores a repeated log pattern in a compact form. A repeat code k[text] means that text is written k times. The text inside can hold more repeat codes, and letters outside any code stand for themselves.
For example, 2[ab3[c]]d expands to the pattern abcccabcccd. The dashboard needs the full pattern. A compact code can have up to 100,000 characters.
Write expand_code(code).
code is made of lowercase letters, digits and the brackets [ and ]. It is valid: every [ has a matching ], and every [ is preceded by a count.Input: code = "2[ab3[c]]d"
Output: "abcccabcccd"Read the characters once. Letters go into the text, and digits build a count. A [ remembers where its group starts in the text, and its count.
A ] takes that note off the stack. It adds the group's text the rest of the times.
| Character | What happens | Text so far | Stack (start, count) |
|---|---|---|---|
2 |
count is now 2 | (empty) | (empty) |
[ |
push (start 0, count 2) | (empty) | (0, 2) |
a |
add the letter | a |
(0, 2) |
b |
add the letter | ab |
(0, 2) |
3 |
count is now 3 | ab |
(0, 2) |
[ |
push (start 2, count 3) | ab |
(0, 2), (2, 3) |
c |
add the letter | abc |
(0, 2), (2, 3) |
] |
pop: repeat c 3 times in all |
abccc |
(0, 2) |
] |
pop: repeat abccc 2 times in all |
abcccabccc |
(empty) |
d |
add the letter | abcccabcccd |
(empty) |
The text is abcccabcccd. The inner code 3[c] ended first, which is why it was on top of the stack.
Input: code = "3[a]2[bc]"
Output: "aaabcbc"3[a] gives aaa, and 2[bc] gives bcbc. The two codes are not nested, so they are expanded one after the other.
Input: code = "xyz"
Output: "xyz"There is no repeat code, so every letter stands for itself.
1 ≤ length of code ≤ 10^5code is valid, and a repeat code is never emptyA plan that expands the first closing bracket and rescans from the left costs about n^2 / 16 steps when many codes stand side by side. That is 6 × 10^8 steps for 25,000 codes, which is too slow.
So the work must be close to n + the length of the output in all. Each character should be read once, and each repeated copy made once.