Search~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-921stacks
The advanced search box of a search app lets people group terms with brackets. A query is valid when every ( is closed by a later ), and every ) closes an earlier (.
When a query is not valid, the app offers a repair: it inserts brackets, at any positions, until the query is valid. It wants the repair that adds the fewest brackets. Only the brackets matter here, so a query is a string of ( and ). A query can have up to 100,000 brackets.
Write fewest_additions(query).
query is a string made only of ( and ). It may already be valid.( or ) at any position, any number of times. Brackets already in the query are not removed or moved.Input: query = "())(()"
Output: 2Read the brackets from left to right and count the ( that are still waiting for a ). A ) closes a waiting ( if there is one. If none is waiting, that ) has no partner, so a ( must be added in front of it.
| Position | Bracket | Waiting ( before |
What happens | Added so far | Waiting after |
|---|---|---|---|---|---|
| 0 | ( |
0 | waits for a ) |
0 | 1 |
| 1 | ) |
1 | closes a waiting ( |
0 | 0 |
| 2 | ) |
0 | no ( to close: add a ( |
1 | 0 |
| 3 | ( |
0 | waits for a ) |
1 | 1 |
| 4 | ( |
1 | waits for a ) |
1 | 2 |
| 5 | ) |
2 | closes a waiting ( |
1 | 1 |
One ( is still waiting at the end, so one ) must be added after it. In all, 1 + 1 = 2 brackets are added.
Input: query = "()"
Output: 0The pair closes itself, so no bracket is added.
Input: query = ")("
Output: 2The ) comes first, with nothing to close, so a ( is added before it. The ( at the end has nothing after it, so a ) is added. That is 2.
1 ≤ length of query ≤ 10^5query is made only of ( and )A plan that deletes one matched pair and re-scans from the left costs about n^2 / 8 steps for a deeply nested query. That is 10^9 steps for 100,000 brackets, which is too slow.
So the work must be close to n steps in all. Each bracket should be looked at once, and matched as soon as it is read.