#1614
Maximum Nesting Depth of the Parentheses
EasyStringStackStackGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force approach but focuses on a single pass through the string while maintaining the current depth and maximum depth. This approach ensures we only traverse the string once, making it more efficient.
⚙️
Algorithm
5 steps- 1Step 1: Initialize `current_depth` and `max_depth` to 0.
- 2Step 2: Loop through each character in the string.
- 3Step 3: Increase `current_depth` for '(', and update `max_depth` if necessary.
- 4Step 4: Decrease `current_depth` for ')'.
- 5Step 5: Return `max_depth` at the end.
solution.py10 lines
1def maxDepth(s):
2 current_depth = 0
3 max_depth = 0
4 for char in s:
5 if char == '(':
6 current_depth += 1
7 max_depth = max(max_depth, current_depth)
8 elif char == ')':
9 current_depth -= 1
10 return max_depthℹ
Complexity note: The optimal solution runs in O(n) time since we only make a single pass through the string, and we use O(1) space as we only need a few variables to track the current and maximum depth.
- 1The maximum depth is determined by counting the number of nested parentheses.
- 2Each opening parenthesis increases depth, while each closing parenthesis decreases it.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.