LeetCode 1614: Maximum Nesting Depth of the Parentheses Solution

Master LeetCode problem 1614 (Maximum Nesting Depth of the Parentheses), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1614. Maximum Nesting Depth of the Parentheses

Problem Explanation

Explanation

To find the maximum nesting depth of parentheses in a given valid parentheses string, we can use a simple algorithm. We iterate through the string character by character and maintain a count of open parentheses. The maximum depth encountered during this iteration will be our answer.

Algorithm:

  1. Initialize variables maxDepth and currentDepth to 0.
  2. Iterate through each character in the input string.
  3. If the character is an opening parenthesis '(', increment currentDepth by 1.
  4. Update maxDepth to be the maximum of maxDepth and currentDepth.
  5. If the character is a closing parenthesis ')', decrement currentDepth by 1.
  6. Return maxDepth as the result.

Time Complexity: O(n) where n is the length of the input string. Space Complexity: O(1) as we are using constant extra space.

Solution Code

class Solution {
    public int maxDepth(String s) {
        int maxDepth = 0;
        int currentDepth = 0;
        
        for (char c : s.toCharArray()) {
            if (c == '(') {
                currentDepth++;
                maxDepth = Math.max(maxDepth, currentDepth);
            } else if (c == ')') {
                currentDepth--;
            }
        }
        
        return maxDepth;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1614 (Maximum Nesting Depth of the Parentheses)?

This page provides optimized solutions for LeetCode problem 1614 (Maximum Nesting Depth of the Parentheses) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1614 (Maximum Nesting Depth of the Parentheses)?

The time complexity for LeetCode 1614 (Maximum Nesting Depth of the Parentheses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1614 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1614 in Java, C++, or Python.

Back to LeetCode Solutions