Search~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-678greedy
You work on the search box of an app. Advanced filters use round brackets to group terms, such as (sale)(new). When a filter is saved as a template, the editor may replace a bracket with a placeholder *.
A placeholder can be read as an opening bracket, a closing bracket, or nothing. Your team lead asks: "Can the placeholders be read in some way so that every bracket is matched?"
Write can_balance(pattern).
pattern is a string of (, ) and *.* can be read as (, as ), or as an empty string. You choose a reading for each * on its own.( has a later ) that closes it, every ) has an earlier (, and none is left over.true when some reading of the stars makes the brackets match, and false otherwise.Input: pattern = "(*)(*"
Output: trueKeep two numbers: low, the fewest unclosed ( over every reading, and high, the most. A star lowers low by 1 and raises high by 1. If low would go below 0, set it to 0.
| Character | low | high | Meaning |
|---|---|---|---|
| ( | 1 | 1 | one bracket open in every reading |
| * | 0 | 2 | the star can close it, or open another |
| ) | 0 | 1 | one bracket closed |
| ( | 1 | 2 | a new one opens |
| * | 0 | 3 | the star can close it |
The string ends with low = 0, so some reading matches. One is ()() with the stars read as ) and as nothing.
Input: pattern = "*))"
Output: falseThe star can close one bracket at most, but there are two ) and nothing to open. After the last character high would be -1, so no reading works.
Input: pattern = "*"
Output: trueRead the star as an empty string. There are no brackets left to match.
1 ≤ len(pattern) ≤ 100,000pattern holds only (, ) and *The string can have 100,000 characters, and every star has 3 readings. With 20 stars that is 3^20, about 3.5 billion readings. One pass that keeps two numbers costs 100,000 steps.