#1111
Maximum Nesting Depth of Two Valid Parentheses Strings
MediumStringStackGreedyDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a greedy strategy to assign parentheses to two subsequences A and B in a balanced manner. By alternating between A and B for each '(' and ')' character, we ensure that both subsequences maintain valid nesting depths.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an answer array of the same length as the input string, filled with zeros.
- 2Step 2: Use a counter to track the depth of nesting as you iterate through the string.
- 3Step 3: For each '(', increment the depth and assign it to A or B based on the current depth.
- 4Step 4: For each ')', decrement the depth and assign it to A or B accordingly.
solution.py11 lines
1def maxNestingDepth(seq):
2 answer = [0] * len(seq)
3 depth = 0
4 for i, char in enumerate(seq):
5 if char == '(': # Increment depth
6 depth += 1
7 answer[i] = depth % 2 # Assign to A or B
8 else: # Decrement depth
9 answer[i] = depth % 2 # Assign to A or B
10 depth -= 1
11 return answerℹ
Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the answer array that stores the result.
- 1The depth of nesting can be controlled by how we distribute parentheses between two subsequences.
- 2Using a greedy approach allows us to minimize the maximum depth efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.