Keep a count variable and keep only the substring that is a ‘valid parentheses string’ i.e. count >= 0
where count is incremented for (
and decremented for )
.
Any parentheses that makes the string ‘invalid’, just ignore it.
There need to be two passes, because when going from left to right we can ignore all closing parentheses, but there could be some opening ones that are just extra. For that, make a second pass as well on the reversed string.
Code
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since we visit each character in the string only once in one pass.
-
Memory
The memory usage is since we use the
result
andfiltered
array to store.
— A