Maximum Nesting Depth of the Parentheses — LeetCode 1614 Python Solution
EasyStackString
- Problem
- #1614
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Python solution
Python
class Solution:
def maxDepth(self, s: str) -> int:
ans = d = 0
for c in s:
if c == '(':
d += 1
ans = max(ans, d)
elif c == ')':
d -= 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1614. Maximum Nesting Depth of the Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1614. Maximum Nesting Depth of the Parentheses?
- LeetCode 1614. Maximum Nesting Depth of the Parentheses is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1614. Maximum Nesting Depth of the Parentheses?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 1614. Maximum Nesting Depth of the Parentheses?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1614. Maximum Nesting Depth of the Parentheses cover?
- LeetCode 1614. Maximum Nesting Depth of the Parentheses is tagged Stack and String on LeetCode.