1614. Maximum Nesting Depth of the Parentheses

Intuition

We want to find how deeply nested the parentheses go in a valid string. We can track this by incrementing a depth counter when we see '(', and decrementing it when we see ')'. At every step, we update the maximum depth seen so far.

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(N)\text{O}(N)

Code

public int maxDepth(String parenthesesString) {
    int currentDepth = 0;     // Tracks current depth as we parse
    int maxDepthSeen = 0;     // Tracks the maximum depth encountered

    // Traverse each character in the input string
    for (int i = 0; i < parenthesesString.length(); ++i) {
        char currentChar = parenthesesString.charAt(i);

        // When we open a parenthesis, increase the depth
        if (currentChar == '(') {
            currentDepth++;
        } 
        // When we close a parenthesis, decrease the depth
        else if (currentChar == ')') {
            currentDepth--;
        }

        // Update the max depth seen so far
        maxDepthSeen = Math.max(maxDepthSeen, currentDepth);
    }

    return maxDepthSeen; // Return the deepest nesting level
}

Last updated