String Parentheses : 4April POTD
Day 9/75:
Question: Maximum Nesting Depth of the Parentheses -(Easy)
A string is a valid parentheses string (denoted VPS) if it meets one of the following:
We can similarly define the nesting depth depth(S) of any VPS S as follows:
For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's.
Given a VPS represented as string s, return the nesting depth of s.
Input: s = "(1+(2*3)+((8)/4))+1"
Output: 3
Explanation: Digit 8 is inside of 3 nested parentheses in the string.
Input: s = "(1)+((2))+(((3)))"
Output: 3
?Intuition: Count of maximum open braces is required (max depth)
Approach1: Stack
Stack is the first approach which basically comes ,when we see Parentheses.
Simply traverse the string and push the Open Brace '(' into stack ,calculate max size of stack thereby poping when encounters Closing Brace '('
Return maximum size of stack.
Code : (Stack)
Time Complexity: O(n)
Space Complexity : O(n) - Stack is used.
==========================================
Approach 2: Optimized
Code:
Time Complexity: O(n)
Space Complexity : O(1) - No extra space is used.
Related Question : Maximum Nesting Depth of Two Valid Parentheses Strings