Chat app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1021stacks
A chat app stores the reply structure of a thread as a string of brackets. An opening bracket starts a group of replies, and the matching closing bracket ends it. Groups can sit inside other groups, and groups that are not inside any other group stand side by side.
For the thread list, the app strips the outermost pair of brackets from every top-level group and keeps everything inside. A thread string can have up to 100,000 brackets.
Write strip_outer_layer(threads).
threads is a balanced string of ( and ): every ( is closed by a later ), and every ) closes a (.( that is not inside any other group, and ends at its matching ).Input: threads = "(()())()(())"
Output: "()()()"Read the brackets once and keep a depth: the number of groups that are open. A bracket that opens at depth 0, or closes down to depth 0, is an outermost bracket, so skip it. Keep all the others.
| Position | Bracket | Depth before | Kept? | Output so far |
|---|---|---|---|---|
| 0 | ( |
0 | no: outermost | (empty) |
| 1 | ( |
1 | yes | ( |
| 2 | ) |
2 | yes | () |
| 3 | ( |
1 | yes | ()( |
| 4 | ) |
2 | yes | ()() |
| 5 | ) |
1 | no: outermost | ()() |
| 6 | ( |
0 | no: outermost | ()() |
| 7 | ) |
1 | no: outermost | ()() |
| 8 | ( |
0 | no: outermost | ()() |
| 9 | ( |
1 | yes | ()()( |
| 10 | ) |
2 | yes | ()()() |
| 11 | ) |
1 | no: outermost | ()()() |
The result is ()()(): the first group (()()) gives ()(), the second group () gives nothing, and the third group (()) gives ().
Input: threads = "()()"
Output: ""Both groups hold nothing, so stripping the outer layer leaves an empty string.
Input: threads = "((()))"
Output: "(())"One group, nested three deep. Removing its first and its last bracket leaves (()).
2 ≤ length of threads ≤ 10^5threads is balanced, and made only of ( and )A plan that recounts the open brackets for every bracket costs up to n^2 / 2 steps: 5 × 10^9 for a long string. That is too slow.
So the work must be close to n steps in all. The depth should be kept up to date as you read, not rebuilt each time.