Suppose we have a string, that string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and it satisfies these properties −
It is the empty string, or
It can be written as AB, where A and B are VPS's, or
It can be written as (A), where A is a VPS.
We can also define the nesting depth depth(S) of any VPS S like below −
depth("") = 0
depth(A + B) = max of depth(A), depth(B), where A and B are VPS's
depth("(" + A + ")") = 1 + depth(A), where A is a VPS.
If we have a VPS seq, we have to split it into two disjoint subsequences A and B, such that A and B are VPS's (and length of A + length of B = length of seq). Now if we choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Then we have to find an answer array (of length of seq) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is a part of A, otherwise answer[i] = 1.
So if the input is like "()(())()", then the output will be [1,1,1,0,1,0,1,1]
To solve this, we will follow these steps −
n := length of seq, res := an array of 0s whose length is n
c1, c2 := 0, 0
for i in range 0 to n – 1
if seq[i] = ‘(’
if c1 < c2, then increase c1 by 1, otherwise increase c2 by 1 and res[i] := 1
otherwise
if c1 > c2, then decrease c1 by 1, otherwise decrease c2 by 1 and res[i]:= 1
return res
Let us see the following implementation to get better understanding −
Example
class Solution(object): def maxDepthAfterSplit(self, seq): n = len(seq) res = [0] *n c1,c2= 0,0 for i in range(n): if seq[i] == '(': if c1<c2: c1+=1 else: c2+=1 res[i]=1 else: if c1>c2: c1-=1 else: c2-=1 res[i]=1 return res ob = Solution() print(ob.maxDepthAfterSplit("()(())()"))
Input
"()(())()"
Output
[1, 1, 1, 0, 1, 0, 1, 1]