Taro Logo

Maximum Nesting Depth of the Parentheses

Easy
3 views
21 days ago

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.
Sample Answer
## Nesting Depth of Valid Parentheses String

This problem asks us to find the maximum nesting depth of a valid parentheses string (VPS). A VPS is a string that consists of digits, '+', '-', '*', '/', '(', and ')', and has balanced parentheses. The nesting depth is the maximum number of nested parentheses at any point in the string.

### Brute Force Solution

A brute force solution would involve iterating through all possible substrings and checking if they are valid parentheses strings.  If a substring is a valid parentheses string, we calculate its nesting depth. Finally, we find the maximum of all nesting depths.

However, this approach is inefficient because it involves generating all possible substrings and checking their validity, which can be time-consuming.

### Optimal Solution

We can solve this problem more efficiently by iterating through the string once and keeping track of the current nesting depth. We increment the depth when we encounter an opening parenthesis '(' and decrement it when we encounter a closing parenthesis ')'.  The maximum depth encountered during the iteration is the nesting depth of the VPS.

```python
def max_depth(s: str) -> int:
    """Calculates the maximum nesting depth of a valid parentheses string.

    Args:
        s: The input string.

    Returns:
        The maximum nesting depth of the string.
    """
    max_depth = 0
    current_depth = 0

    for char in s:
        if char == '(':  # Encountered an opening parenthesis
            current_depth += 1
            max_depth = max(max_depth, current_depth)
        elif char == ')':  # Encountered a closing parenthesis
            current_depth -= 1

    return max_depth

Example Usage:

s1 = "(1+(2*3)+((8)/4))+1"
print(f"The nesting depth of '{s1}' is: {max_depth(s1)}")  # Output: 3

s2 = "(1)+((2))+(((3)))"
print(f"The nesting depth of '{s2}' is: {max_depth(s2)}")  # Output: 3

s3 = "()(())((()()))"
print(f"The nesting depth of '{s3}' is: {max_depth(s3)}")  # Output: 3

Big(O) Run-time Analysis

The run-time complexity of this solution is O(n), where n is the length of the string. We iterate through the string once to calculate the nesting depth.

Big(O) Space Usage Analysis

The space complexity of this solution is O(1), as we only use a few constant space variables to store the current depth and maximum depth.

Edge Cases

  1. Empty string: If the input string is empty, the nesting depth is 0. The code handles this correctly because the loop will not execute, and the initial value of max_depth (0) will be returned.
  2. String with no parentheses: If the string contains no parentheses, the nesting depth is 0. The code handles this correctly because the if and elif conditions will never be met, so max_depth will remain 0.
  3. Invalid parentheses string: The problem statement guarantees that the input string is a valid parentheses string. Therefore, we don't need to handle cases where the parentheses are unbalanced (e.g., "(()", ")("). However, in a real-world scenario, we might want to add a check to ensure the string is valid before calculating the nesting depth. This could be done by ensuring that current_depth never goes below 0 and that it is 0 at the end of the iteration.