1111. Maximum Nesting Depth of Two Valid Parentheses Strings
LeetCode Daily Problem: Maximum Nesting Depth of Two Valid Parentheses Strings
On this page
Given a valid parentheses string (VPS) seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). The subsequences may not necessarily be contiguous.
For example, for the sequence 123456789, one possible split is:
A = {1, 3, 5, 7, 9},B = {2, 4, 6, 8}.
This corresponds to the output [0, 1, 0, 1, 0, 1, 0, 1, 0] where 0 indicates membership in A and 1 indicates membership in B.
Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.
Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.
Approach: I'm not sure how to describe this one
My first idea was simply to split the depth evenly: scan once to find the maximum depth, then assign every parenthesis deeper than half to the other group. But that needs two passes.
The official answer uses a different split that needs only one pass: assign by the parity of the nesting level. I thought it was clever. It is still O(n) time and space, not a fundamental breakthrough, but worth learning.
Here is my code:
class Solution:
def maxDepthAfterSplit(self, seq: str) -> list[int]:
dph = []
cur_dph = 1
for i, c in enumerate(seq):
if c == '(':
dph.append(cur_dph)
cur_dph += 1
else:
cur_dph -= 1
dph.append(cur_dph)
max_dph = max(dph)
return [int(d > max_dph//2) for d in dph]Complexity
- Time and space: O(n).