Problem

A string is a valid parentheses string (denoted VPS) if it meets one of the following:

  • It is an empty string "", or a single character not equal to "(" or ")",
  • It can be written as AB (A concatenated with B), where A and B are VPS’s, or
  • It can be written as (A), where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

  • depth("") = 0
  • depth(C) = 0, where C is a string with a single character not equal to "(" or ")".
  • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS’s.
  • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.

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.

Examples

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

Solution

Method 1 - Using counters

To determine the nesting depth of a valid parentheses string:

  1. Initialize a counter current_depth to track the current depth as we traverse the string.
  2. Initialize a variable max_depth to keep track of the maximum depth encountered.
  3. Iterate through each character in the string:
    • Increment current_depth when encountering an opening parenthesis (.
    • Update max_depth if current_depth exceeds it.
    • Decrement current_depth when encountering a closing parenthesis ).
  4. Return the max_depth as the nesting depth of the string.

Code

Java
class Solution {
    public int maxDepth(String s) {
        int currentDepth = 0;
        int maxDepth = 0;
        
        for (char c : s.toCharArray()) {
            if (c == '(') {
                currentDepth++;
                if (currentDepth > maxDepth) {
                    maxDepth = currentDepth;
                }
            } else if (c == ')') {
                currentDepth--;
            }
        }
        
        return maxDepth;
    }
}
Python
class Solution:
    def maxDepth(self, s: str) -> int:
        current_depth = 0
        max_depth = 0

        for c in s:
            if c == '(':
                current_depth += 1
                if current_depth > max_depth:
                    max_depth = current_depth
            elif c == ')':
                current_depth -= 1

        return max_depth

Complexity

  • ⏰ Time complexity: O(n), where n is the length of the string, since we traverse the string once.
  • 🧺 Space complexity: O(1), because we use a fixed amount of additional space regardless of the input size.