1
$\begingroup$

Currently I want to learn the complexity of space, I read a few of the books on it. On this I encountered this example problem. I would just like to know how to show that the following problem $​\in L $ (deterministic logarithmic space).

Input: series of open or closed parentheses

Question: Are these parentheses properly balanced?

Example: $((() ()) (()))$ should be accepted but $()) ()$ should be rejected.​

$\endgroup$

2 Answers 2

6
$\begingroup$

Initialize a counter at zero. Whenever you see "(", increase it by one, and whenever you see ")", decrease it by one. Accept if the counter was always nonnegative and ended up at zero. The counter only takes logarithmic space to store.

$\endgroup$
3
$\begingroup$

This amounts to reading the input string and keeping track of the difference $\delta$ between the number of open and closed parenthesis.

If $\delta$ ever becomes negative, then the input is not properly balanced (at some point there is one more closed parenthesis than open ones). Similarly, if $\delta >0$ at the end of the string, then there are unclosed parentheses and the input is unbalanced.

Otherwise the input is balanced.

Since $\delta$ is always between $-1$ and $n$, only $O(\log n)$ bits are needed to store it. The same applies for the other auxiliary variables you'll need to implement the above algorithm (for example an index to the current character of the input). Hence the problem is in logspace.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.