1614. Maximum Nesting Depth of the Parentheses LeetCode Solution
In this guide, you will get 1614. Maximum Nesting Depth of the Parentheses LeetCode Solution with the best time and space complexity. The solution to Maximum Nesting Depth of the Parentheses problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Nesting Depth of the Parentheses solution in C++
- Maximum Nesting Depth of the Parentheses solution in Java
- Maximum Nesting Depth of the Parentheses solution in Python
- Additional Resources
Problem Statement of Maximum Nesting Depth of the Parentheses
Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.
Example 1:
Input: s = “(1+(2*3)+((8)/4))+1”
Output: 3
Explanation:
Digit 8 is inside of 3 nested parentheses in the string.
Example 2:
Input: s = “(1)+((2))+(((3)))”
Output: 3
Explanation:
Digit 3 is inside of 3 nested parentheses in the string.
Example 3:
Input: s = “()(())((()()))”
Output: 3
Constraints:
1 <= s.length <= 100
s consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.
It is guaranteed that parentheses expression s is a VPS.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
1614. Maximum Nesting Depth of the Parentheses LeetCode Solution in C++
class Solution {
public:
int maxDepth(string s) {
int ans = 0;
int opened = 0;
for (const char c : s)
if (c == '(')
ans = max(ans, ++opened);
else if (c == ')')
--opened;
return ans;
}
};
/* code provided by PROGIEZ */
1614. Maximum Nesting Depth of the Parentheses LeetCode Solution in Java
class Solution {
public int maxDepth(String s) {
int ans = 0;
int opened = 0;
for (final char c : s.toCharArray())
if (c == '(')
ans = Math.max(ans, ++opened);
else if (c == ')')
--opened;
return ans;
}
}
// code provided by PROGIEZ
1614. Maximum Nesting Depth of the Parentheses LeetCode Solution in Python
class Solution:
def maxDepth(self, s: str) -> int:
ans = 0
opened = 0
for c in s:
if c == '(':
opened += 1
ans = max(ans, opened)
elif c == ')':
opened -= 1
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.