The unclosed doors
- O(n) · Medium
- Full plan
- Python
- JavaScript
- strings
- loops
Problem
Albor Manor woke up in silence. During the night, someone wrote a ( in the logbook every time a door opened and a ) every time one closed, but a few entries slipped past them.
The log makes sense if every ) closes a ( that came before it and nothing is left open at the end. Write a function that takes the log (a string made only of ( and ), possibly empty) and returns, as an integer, the smallest number of characters you'd have to add for it to make sense.
With ())( you return 2: the second ) has nothing to close and needs a ( before it, and the last ( is left open and needs a ). A stray ) isn't fixed by a ( that comes later: )( also gives 2.
An empty log already makes sense: you return 0.
Examples
One left open
"(()" → 1
All in order
"()()" → 0
Closes before opening
")(" → 2
An empty log
"" → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def missing_marks(log):
passJavaScript
function missingMarks(log) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.