Level 1 How many to delete
s contains only ( and ). A string is balanced if every ( can be paired with a later ) and nothing is left unpaired. The empty string is balanced.
Write min_deletions(s: str) -> int, the fewest characters you must delete from s so the rest is balanced. s has up to a million characters.
⭐ Bonus: repeatedly deleting "()" pairs still passes; a speed test on a million characters earns a star in O(n) time (O(1) extra space is the classic follow-up).
min_deletions("())(") # 2
min_deletions("(()") # 1
min_deletions("()()") # 0
Show hint
you don't need to remember which characters are unmatched, only how many of each kind.