Maximum Nesting Depth of Two Valid Parentheses Strings - Problem
A string is a valid parentheses string (denoted VPS) if and only if it consists of ( and ) characters only, and:
- It is the empty string, or
- It can be written as
AB(A concatenated with B), where A and B are VPS's, or - It can be written as
(A), where A is a VPS.
We can similarly define the nesting depth depth(S) of any VPS S as follows:
depth("") = 0depth(A + B) = max(depth(A), depth(B)), where A and B are VPS'sdepth("(" + A + ")") = 1 + depth(A), where A is a VPS.
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(", "(()" are not VPS's.
Given a 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).
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.
Input & Output
Example 1 — Balanced Distribution
$
Input:
seq = "(()())"
›
Output:
[0,1,1,0,1,0]
💡 Note:
Split into A="()()" (depth 1) and B="()" (depth 1). The maximum depth is min(1,1) = 1, which is optimal.
Example 2 — Simple Case
$
Input:
seq = "()(())"
›
Output:
[0,0,1,1,1,1]
💡 Note:
Split into A="()" (depth 1) and B="()()" (depth 1). Both have depth 1, giving maximum depth of 1.
Example 3 — Nested Structure
$
Input:
seq = "(((())))"
›
Output:
[0,1,0,1,1,0,1,0]
💡 Note:
Alternating assignment distributes nested levels evenly: A="(())" (depth 2) and B="(())" (depth 2), max depth = 2.
Constraints
- 1 ≤ seq.length ≤ 104
- seq is a valid parentheses string
Visualization
Tap to expand
Understanding the Visualization
1
Input
Valid parentheses string like "(()())"
2
Split Strategy
Alternate assignment based on nesting depth
3
Output
Array indicating group assignment for each character
Key Takeaway
🎯 Key Insight: Alternating assignment based on nesting depth parity distributes the load evenly between two groups
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code