ICPC Asia Pacific Championship 2026 — Solution M. Deformed Balance

M  Deformed Balance

In what follows, we write an open parenthesis as L and a close parenthesis as R. The BNF formulation of the deformed strings can be defined as follows.

\[E ::= \texttt{R} \mid E\ \texttt{R}\ E \mid \texttt{L}\ E\ \texttt{L}.\]

Consider a slightly modified version of \(E\), where the terminal symbol L is replaced by either ‘{’ or ‘}’:

\[E' ::= \texttt{R} \mid E'\ \texttt{R}\ E' \mid \texttt{\{}\ E'\ \texttt{\}}.\]

Suppose that a string \(S'\) conforms to \(E'\). The following can be proven by induction.

Thus, \(S'\) has a form {{{ ... {{{ R }}} ... }}} R {{{ ... }}} R }}} ... }}} R {{{ ... {{{ R }}} .... Two or more R’s may appear contiguously. Conversely, if a string \(S'\) has this form and the brackets {} are balanced, we can generate \(S'\) using \(E'\):

Hence, if we want to determine whether a string consisting of R and L conforms to \(E\), we can do so by replacing the L’s with either ‘{’ or ‘}’ and then checking if that conforms to \(E'\).

For determining whether a string \(W\) has a deformed balance or not, we track two values \(x\) and \(y\) from the beginning, where \(x\) is the current nesting level for the parentheses LR, and \(y\) is the nesting level for the brackets {}. During the tracking \(x, y \ge 0\) must be always hold. At the end of the string, \((x, y) = (1, 0)\) must hold for the string \(W\) to have a deformed balance.

The values of \((x, y)\) change as follows:

Now, let’s move on to the original problem. For the input string \(S\), we can prepend and append some characters to \(S\) to form \(S' = X + S + Y\).

Total time complexity is \(O(n)\).