Maximum Nesting Depth of Two Valid Parentheses Strings

medium parentheses greedy stack

Problem

A valid parentheses string (VPS) is balanced and well-formed. Given a VPS seq, split it into two disjoint subsequences A and B, both valid, so that max(depth(A), depth(B)) is as small as possible. Return an array answer of the same length where answer[i] is 0 if character seq[i] goes to A and 1 if it goes to B.

Inputseq = "(()())"
Output[0, 1, 1, 1, 1, 0]
The full string nests to depth 2. Splitting by depth parity gives each subsequence depth 1, so the larger depth is minimized.

def max_depth_after_split(seq):
    ans = [0] * len(seq)
    depth = 0
    for i, c in enumerate(seq):
        if c == '(':
            ans[i] = depth % 2
            depth += 1
        else:
            depth -= 1
            ans[i] = depth % 2
    return ans
function maxDepthAfterSplit(seq) {
  const ans = new Array(seq.length);
  let depth = 0;
  for (let i = 0; i < seq.length; i++) {
    if (seq[i] === '(') {
      ans[i] = depth % 2;
      depth++;
    } else {
      depth--;
      ans[i] = depth % 2;
    }
  }
  return ans;
}
class Solution {
    public int[] maxDepthAfterSplit(String seq) {
        int[] ans = new int[seq.length()];
        int depth = 0;
        for (int i = 0; i < seq.length(); i++) {
            if (seq.charAt(i) == '(') {
                ans[i] = depth % 2;
                depth++;
            } else {
                depth--;
                ans[i] = depth % 2;
            }
        }
        return ans;
    }
}
vector<int> maxDepthAfterSplit(string seq) {
    vector<int> ans(seq.size());
    int depth = 0;
    for (int i = 0; i < (int)seq.size(); i++) {
        if (seq[i] == '(') {
            ans[i] = depth % 2;
            depth++;
        } else {
            depth--;
            ans[i] = depth % 2;
        }
    }
    return ans;
}
Time: O(n) Space: O(n)