Monitoring~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-32stacks
A tracing tool writes ( when a task starts and ) when a task ends. A trace can be damaged: some marks are lost, so a ) may have no ( before it, and a ( may never be closed.
A stretch of consecutive marks is well-formed when every start in it has its end inside it, properly nested. The engineers want the length of the longest well-formed stretch that is left in a damaged trace. A trace can have up to 100,000 marks.
Write longest_balanced_run(trace).
trace is a string made only of ( and ). It may be damaged.trace: no character is skipped. It is well-formed when every ( in it is closed by a later ) in it, and every ) in it closes a ( in it.0 if there is none.Input: trace = "(()))()(()())"
Output: 8Keep a stack of positions. The bottom of the stack is the position right before the stretch that is being built. A ( pushes its position. A ) pops, and then the stretch runs from right after the new top to here.
| Position | Mark | What happens | Stack after (positions) | Longest so far |
|---|---|---|---|---|
| 0 | ( |
a start: push its position | -1, 0 | 0 |
| 1 | ( |
a start: push its position | -1, 0, 1 | 0 |
| 2 | ) |
closes a start: the stretch is 2 long | -1, 0 | 2 |
| 3 | ) |
closes a start: the stretch is 4 long | -1 | 4 |
| 4 | ) |
no start was waiting: this end is the new bottom | 4 | 4 |
| 5 | ( |
a start: push its position | 4, 5 | 4 |
| 6 | ) |
closes a start: the stretch is 2 long | 4 | 4 |
| 7 | ( |
a start: push its position | 4, 7 | 4 |
| 8 | ( |
a start: push its position | 4, 7, 8 | 4 |
| 9 | ) |
closes a start: the stretch is 2 long | 4, 7 | 4 |
| 10 | ( |
a start: push its position | 4, 7, 10 | 4 |
| 11 | ) |
closes a start: the stretch is 4 long | 4, 7 | 4 |
| 12 | ) |
closes a start: the stretch is 8 long | 4 | 8 |
The longest stretch is 8, from position 5 to position 12: ()(()()). The ) at position 4 had no start waiting, so it became the new bottom and blocked every stretch that began before it.
Input: trace = "()(()"
Output: 2The pairs at positions 0 and 1, and at positions 3 and 4, are separate. The ( at position 2 is never closed, and it sits between them, so no stretch is longer than 2.
Input: trace = "(()"
Output: 2The first ( is never closed, so the stretch cannot include it. The pair at positions 1 and 2 is well-formed and has length 2.
1 ≤ length of trace ≤ 10^5trace is made only of ( and )A plan that tries every start and reads forward costs up to n^2 / 2 steps when the trace is valid all the way: 5 × 10^9 for 100,000 marks. That is too slow.
So the work must be close to n steps in all. Each mark should be read once, and the stack should tell you where the current stretch began.