Skip to content

1111. Maximum Nesting Depth of Two Valid Parentheses Strings 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<int> maxDepthAfterSplit(string seq) {
    vector<int> ans;
    int depth = 1;

    // Put all odd-depth parentheses in one group and even-depth parentheses in
    // the other group.
    for (const char c : seq)
      if (c == '(')
        ans.push_back(++depth % 2);
      else
        ans.push_back(depth-- % 2);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int[] maxDepthAfterSplit(String seq) {
    int[] ans = new int[seq.length()];
    int depth = 1;

    // Put all odd-depth parentheses in one group and even-depth parentheses in
    // the other group.
    for (int i = 0; i < seq.length(); ++i)
      if (seq.charAt(i) == '(')
        ans[i] = ++depth % 2;
      else
        ans[i] = depth-- % 2;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def maxDepthAfterSplit(self, seq: str) -> list[int]:
    ans = []
    depth = 1

    # Put all odd-depth parentheses in one group and even-depth parentheses in the other group.
    for c in seq:
      if c == '(':
        depth += 1
        ans.append(depth % 2)
      else:
        ans.append(depth % 2)
        depth -= 1

    return ans