Editorial for Baltic OI '05 P2 - LISP
Submitting an official solution before solving the problem yourself is a bannable offence.
We get a linear-time algorithm via the following result:
Theorem: If a string can be balanced by choosing suitable values for its magic parentheses ]
, then it can be balanced in a way which chooses for all but the last (rightmost) magic parenthesis ]
.
Proof: Consider the nondeterministic pushdown automaton accepting the correctly parenthesized strings without magic parentheses. Incorporate magic parentheses into it by guessing nondeterministically the correct number of opening parentheses (
to pop whenever a magic parenthesis is read.
Consider any accepting computation of this automaton. Consider any stage where a magic parenthesis is read, more than one pops are guessed for it, and the input still contains another magic parenthesis. Let be the subsequent stage where this next magic parenthesis is read. Modify this computation to guess one less pop at stage and one more pop at stage . This modified computation is accepting as well:
- Before stage , proceeds exactly as .
- Between stages and (inclusive), proceeds as except that the stack has one more opening parenthesis, and this extra parenthesis cannot cause to reject due to the structure of this automaton.
- After stage , again proceeds exactly as .
The result follows by iterating the argument above until no such stage exists. QED
The automaton used in the proof yields the required algorithm.
Comments
Here's an alternate proof of the theorem.
Proof: Suppose the string can be balanced by choosing suitable values for its
]
. In other words, is a solution.Suppose there is some index where . The goal is to decrement and increment . Take a
)
from and move it rightwards to . There are 2 cases when moving)
rightwards by 1 character:Swap
)
with)
. This does not change the string.Swap
)
with(
. In other words,)(
becomes()
.Claim: In any balanced string, changing
)(
to()
results in another balanced string. The proof is an exercise. (Hint:)(
is a "decrement, increment" and()
is an "increment, decrement")During every swap, the string remains balanced. Therefore, it's possible to decrement and increment to get another balanced string. Do this repeatedly until . QED