Maximum Nesting Depth of the Parentheses in Java12 May 2025 | 8 min read The concept of Maximum Nesting Depth of Parentheses is commonly encountered in string parsing and mathematical expression evaluation. It refers to the deepest level of nested parentheses within a given string. Given a string containing only the characters '(' and ')' our objective is to determine the maximum depth of nested parentheses. The depth increases when encountering an opening parenthesis '(' and decreases when encountering a closing parenthesis ')'. The highest value attained in this process is the result. ExamplesExample 1: Input: String s = "((3+2)*((5-1)+2))"; Output: 3 Explanation There are several sets of nested parentheses in this expression. The maximum nesting depth is at the innermost nesting level within "((5-1)+2)", which has a depth of 3. The depth begins at 0 and rises whenever an opening parenthesis '(' is met. The first parenthesis at position 0 raises the depth to 1, and the second opening parenthesis at position 1 raises to 2. Continuing a third opening parenthesis at position 7 raises the depth to 3, which is the highest nesting depth in this expression. When closing parentheses ')' are met, the depth is reduced accordingly. The maximum depth recorded during the traversal of the string is 3, which is the final output. Example 2: Input: String s = "(4+5)-(6/2)+(7*3)"; Output: 1 Explanation In this case, the given expression contains multiple pairs of parentheses, but none of them are nested within each other. Every parenthesis set is standalone and has a depth of only 1. While we traverse the string, the depth becomes 1 as we encounter an opening parenthesis '(' and drops back to 0 when we encounter a closing parenthesis ')'. Because there is no nesting within any parenthesis set, the depth never goes higher than 1. The answer is thus 1. Example 3: Input: String s = "((((1+(2))))+((((3+(4*5))))))”; Output : 6 Explanation The depth begins at 0 and is incremented each time an opening parenthesis '(' is found. The first parenthesis at index 0 raises the depth to 1, followed by the second one at index 1, raising it to 2, and the third one at index 2, taking it to 3, and the fourth one at index 3, raising it to 4. The nesting continues with the fifth opening parenthesis at index 4, taking it to a depth of 5. Further along in the expression, another very deeply nested segment "((((3+(4*5)))))" is seen, where a further opening parenthesis at index 14 takes the depth to 6. Continuing with the traversal, each closing parenthesis ')' brings the depth down, but the highest recorded depth is 6, which is the output. Approach 1: Using IterationAlgorithmStep 1: Declare two integer variables, maxDepth to keep a record of the highest depth reached and currentDepth to keep a check on the depth while traversing the string. Initialize both the variables to zero at the start. Step 2: Loop through every character of the input strings. When an opening parenthesis '(' is encountered, increase currentDepth by one and update maxDepth if currentDepth is higher than the highest depth found so far. Step 3: If a closing parenthesis ')' is read, then decrement currentDepth by one to indicate the decrease in nesting. As the parentheses are properly formed, currentDepth will never go below zero. Step 4: Keep iterating over the string until all characters have been scanned and keeping track of counting all opening and closing parentheses correctly. Step 5: Once traversal is done, then return maxDepth as the result, which is the maximum nesting level found in the input expression. Step 6: The solution effectively computes the maximum nesting depth in a single pass over the string through a counter-based method without any need for extra data structures. ImplementationOutput: Example 1 - Maximum Depth: 3 Example 2 - Maximum Depth: 1 Example 3 - Maximum Depth: 6 Complexity AnalysisTime Complexity The time complexity of this algorithm is O(n) because each character in the string is processed exactly once. Space Complexity The space complexity is O(1) since only a few integer variables are used, regardless of the input size. Approach 2: Using RecursionAlgorithmStep 1: Begin by declaring a recursive function that goes through each character of the string individually. Keep three variables: the current index to keep track of the position in the string, the current depth to keep a count of open parentheses, and the maximum depth to hold the highest nesting level reached. Step 2: If the index is at the end of the string, return the highest depth seen so far since there is no further processing. If an opening parenthesis '(' is encountered at the current index and then increment the current depth by one and update the maximum depth if the current depth is higher than the previous maximum. Step 3: If a closing parenthesis ')' is found, reduce the current depth by one since it indicates the end of a nested section. For any other character that is not a parenthesis, proceed to the next index without modifying the depth values. Step 4: Proceed recursively until the entire string characters are handled. For each recursive call, modify the depth values as appropriate and make sure that the function visits each character of the input string. Step 5: After the recursion is finished then return the highest depth ever recorded, as it is the deepest nesting level of the parentheses in the provided expression. ImplementationOutput: Example 1 - Maximum Depth: 3 Example 2 - Maximum Depth: 1 Example 3 - Maximum Depth: 6 Complexity AnalysisTime Complexity The time complexity of this approach is O(n) because each character is processed once. Space Complexity The space complexity is O(n) due to the recursive call stack, which can grow proportionally to the depth of the input. Approach 3: Using StackAlgorithmStep 1: Initialize an empty stack to keep track of opening parentheses and a variable to hold the maximum depth reached. Iterate over the input string, character by character, and look for opening or closing parentheses. Step 2: If an opening parenthesis '(' is encountered, push it onto the stack and increment the maximum depth according to the current size of the stack. If a closing parenthesis ')' is encountered, pop an element from the stack as it marks the end of a nested section. Step 3: Keep processing the string while keeping track of only the valid parentheses and ignoring all the rest of the characters like numbers and operators. Step 4: The depth grows with every level of nested parentheses and drops as closing parentheses are reached. Step 5: When the whole string has been processed, the greatest depth reached is returned as the result. ImplementationOutput: Example 1 - Maximum Depth: 3 Example 2 - Maximum Depth: 1 Example 3 - Maximum Depth: 6 Complexity AnalysisTime Complexity The time complexity is O(n) because each character in the string is processed exactly once. Space Complexity The space complexity is O(n) in the worst case, where the stack stores a large number of nested parentheses, but in most cases, the space usage is significantly lower. Next TopicCountDownLatch in Java |
Vertical zig-zag traversal of a tree in Java
The goal is to get the outcome of the items in the Vertical Zig-Zag traversal order given a Binary Tree. A tree's vertical zigzag traversal is described as follows: List the first level's elements in the correct order from right to left; if no parts remain, move...
6 min read
Nth Term of Geometric Progression in Java
Three numbers are given. The first number is the first term of the geometric progression. The second number is the common ratio of the geometric progression, and the third number is the nth term that has to be computed. Example 1: Input int a1 = 5, // first term int...
4 min read
DecimalFormat getMultiplier() method in Java
One of the built-in methods in java.text is getMultiplier(). To get the multiplier to be used in many formats, such as percentage, percentile, etc., the Java class DecimalFomrat is utilized. Syntax: public int getMultiplier() Parameters: No parameters are accepted by this method. Return Value: The multiplier value that can be...
2 min read
How to Pass an Array to Function in Java
? Java, a powerful programming language, provides a number of efficient ways to handle and use arrays. Passing arrays to functions is a crucial part of array manipulation. Programmers can directly manipulate array items by performing actions on them by giving arrays as function parameters. In this...
8 min read
How to Iterate List in Java
In Java, List is is an interface of the Collection framework. It provides us to maintain the ordered collection of objects. The implementation classes of List interface are ArrayList, LinkedList, Stack, and Vector. The ArrayList and LinkedList are widely used in Java. In this section, we...
4 min read
CompositeName equals() method in Java with Examples
The javax.naming.CompositeName class has equals() function. The CompositeName class is used to determine whether or not two objects are equal by comparing this CompositeName with the given object that was passed as a parameter. The equals() method returns true if the objects are equal; otherwise, it...
6 min read
Bernoulli number in Java
Bernoulli numbers are the special type of numbers that plays an important role in number theory and analysis. These numbers are mainly used in series expansions of several trigonometric, gamma, hyperbolic functions, etc. Nth Bernoulli number is denoted by Bn that can be defined by the following...
7 min read
Colossal Numbers in Java
Java, as a versatile and powerful programming language, is well-equipped to handle a wide range of mathematical operations, including those involving colossal numbers. Colossal numbers, often far beyond the range of standard data types like int and long, require specialized handling. In this section, we will...
5 min read
Display Unique Rows in a Binary Matrix in Java
In this section, we will discuss how one can display unique rows in a binary matrix in Java. In this problem, a binary matrix is given and we have to identify, and then print the unique rows of the given binary matrix. Example 1: Explanation: In the above input...
21 min read
Find the Largest Palindrome Divisible by K in Java
Two positive integers, n, and k, are given. In the case where x is a palindrome, the number is said to be k-palindromic. By k, x is divisible. Return, as a string, the greatest k-palindromic integer with n digits. Example 1: Input: int N = 2 int k = 3 Output: The...
24 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India