Find maximum depth of nested parenthesis in a string
Last Updated :
06 Feb, 2023
We are given a string having parenthesis like below
“( ((X)) (((Y))) )”
We need to find the maximum depth of balanced parenthesis, like 4 in the above example. Since ‘Y’ is surrounded by 4 balanced parentheses.
If parenthesis is unbalanced then return -1.
Examples :
Input : S = "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)";
Output : 4
Input : S = "( p((q)) ((s)t) )";
Output : 3
Input : S = "";
Output : 0
Input : S = "b) (c) ()";
Output : -1
Input : S = "(b) ((c) ()"
Output : -1
Method 1 (Uses Stack):
A simple solution is to use a stack that keeps track of current open brackets.
- Create a stack.
- Traverse the string, do following for every character
- If current character is ‘(’ push it to the stack .
- If character is ‘)’, pop an element.
- Maintain maximum count during the traversal.
Below is the code implementation of the algorithm.
C++
// A C++ program to find the maximum depth of nested
// parenthesis in a given expression
#include <bits/stdc++.h>
using namespace std;
int maxDepth(string& s)
{
int count = 0;
stack<int> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
st.push(i); // pushing the bracket in the stack
else if (s[i] == ')') {
if (count < st.size())
count = st.size();
/*keeping track of the parenthesis and storing
it before removing it when it gets balanced*/
st.pop();
}
}
return count;
}
// Driver program
int main()
{
string s = "( ((X)) (((Y))) )";
cout << maxDepth(s);
// This code is contributed by rakeshsahni
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
public static int maxDepth(String s) {
int count=0;
Stack<Integer> st = new Stack<>();
for(int i=0;i<s.length();i++)
{
if(s.charAt(i) == '(')
st.push(i);//pushing the bracket in the stack
else if(s.charAt(i) == ')')
{
if(count < st.size())
count = st.size();
/*keeping track of the parenthesis and storing it before removing
it when it gets balanced*/
st.pop();
}
}
return count;
}
public static void main (String[] args) {
System.out.println(maxDepth("( ((X)) (((Y))) )"));
}
}
Python3
# Python code to implement the approach
def maxDepth(s):
count = 0
st = []
for i in range(len(s)):
if (s[i] == '('):
st.append(i) # pushing the bracket in the stack
elif (s[i] == ')'):
if (count < len(st)):
count = len(st)
# keeping track of the parenthesis and storing
# it before removing it when it gets balanced
st.pop()
return count
# Driver program
s = "( ((X)) (((Y))) )"
print(maxDepth(s))
# This code is contributed by shinjanpatra
C#
//C# program to find the maximum depth
//of nested parenthesis in a string
using System;
using System.Collections;
public class GFG{
static int maxDepth(string s){
int count=0;
Stack st = new Stack();
for(int i=0;i<s.Length;i++)
{
if(s[i]=='('){
st.Push(i);//pushing the bracket in the stack
}else{
if(s[i]==')'){
if(count<st.Count){
count=st.Count;
}
/*keeping track of the parenthesis and storing it before removing
it when it gets balanced*/
st.Pop();
}
}
}
return count;
}
//Driver Code
static public void Main (){
Console.Write(maxDepth("( ((X)) (((Y))) )"));//Function call
}
}
//This code is contributed by shruti456rawal
JavaScript
<script>
// JavaScript code to implement the approach
function maxDepth(s){
let count = 0
let st = []
for(let i=0;i<s.length;i++){
if (s[i] == '(')
st.push(i) // pushing the bracket in the stack
else if (s[i] == ')'){
if (count < st.length)
count = st.length
// keeping track of the parenthesis and storing
// it before removing it when it gets balanced
st.pop()
}
}
return count
}
// Driver program
let s = "( ((X)) (((Y))) )"
document.write(maxDepth(s),"</br>")
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(N) where n is number of elements in given string. As, we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(N), as we are using extra space for stack.
Method 2 ( O(1) auxiliary space ):
This can also be done without using stack.
- 1) Take two variables max and current_max, initialize both of them as 0.
- 2) Traverse the string, do following for every character
- If current character is ‘(’, increment current_max and update max value if required.
- If character is ‘)’. Check if current_max is positive or not (this condition ensure that parenthesis are balanced).
If positive that means we previously had a ‘(’ character
so decrement current_max without worry.
If not positive then the parenthesis are not balanced.
Thus return -1.
- If current_max is not 0, then return -1 to ensure that the parenthesis
are balanced. Else return max
Below is the implementation of the above algorithm.
C++
// A C++ program to find the maximum depth of nested
// parenthesis in a given expression
#include <iostream>
using namespace std;
// function takes a string and returns the
// maximum depth nested parenthesis
int maxDepth(string S)
{
int current_max = 0; // current count
int max = 0; // overall maximum count
int n = S.length();
// Traverse the input string
for (int i = 0; i < n; i++)
{
if (S[i] == '(')
{
current_max++;
// update max if required
if (current_max > max)
max = current_max;
}
else if (S[i] == ')')
{
if (current_max > 0)
current_max--;
else
return -1;
}
}
// finally check for unbalanced string
if (current_max != 0)
return -1;
return max;
}
// Driver program
int main()
{
string s = "( ((X)) (((Y))) )";
cout << maxDepth(s);
return 0;
}
Java
//Java program to find the maximum depth of nested
// parenthesis in a given expression
class GFG {
// function takes a string and returns the
// maximum depth nested parenthesis
static int maxDepth(String S) {
int current_max = 0; // current count
int max = 0; // overall maximum count
int n = S.length();
// Traverse the input string
for (int i = 0; i < n; i++) {
if (S.charAt(i) == '(') {
current_max++;
// update max if required
if (current_max > max) {
max = current_max;
}
} else if (S.charAt(i) == ')') {
if (current_max > 0) {
current_max--;
} else {
return -1;
}
}
}
// finally check for unbalanced string
if (current_max != 0) {
return -1;
}
return max;
}
// Driver program
public static void main(String[] args) {
String s = "( ((X)) (((Y))) )";
System.out.println(maxDepth(s));
}
}
Python3
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
current_max = 0
max = 0
n = len(S)
# Traverse the input string
for i in range(n):
if S[i] == '(':
current_max += 1
if current_max > max:
max = current_max
else if S[i] == ')':
if current_max > 0:
current_max -= 1
else:
return -1
# finally check for unbalanced string
if current_max != 0:
return -1
return max
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
# This code is contributed by BHAVYA JAIN
C#
// C# program to find the
// maximum depth of nested
// parenthesis in a given expression
using System;
class GFG {
// function takes a string
// and returns the maximum
// depth nested parenthesis
static int maxDepth(string S)
{
// current count
int current_max = 0;
// overall maximum count
int max = 0;
int n = S.Length;
// Traverse the input string
for (int i = 0; i < n; i++)
{
if (S[i] == '(')
{
current_max++;
// update max if required
if (current_max > max)
{
max = current_max;
}
}
else if (S[i] == ')')
{
if (current_max > 0)
{
current_max--;
}
else
{
return -1;
}
}
}
// finally check for unbalanced string
if (current_max != 0)
{
return -1;
}
return max;
}
// Driver program
public static void Main()
{
string s = "(((X)) (((Y))))";
Console.Write(maxDepth(s));
}
}
// This code is contributed by Chitranayal
PHP
<?php
// A PHP program to find the
// maximum depth of nested
// parenthesis in a given
// expression
// function takes a string
// and returns the maximum
// depth nested parenthesis
function maxDepth($S)
{
// current count
$current_max = 0;
// overall maximum count
$max = 0;
$n = strlen($S);
// Traverse the input string
for ($i = 0; $i < $n; $i++)
{
if ($S[$i] == '(')
{
$current_max++;
// update max if required
if ($current_max> $max)
$max = $current_max;
}
else if ($S[$i] == ')')
{
if ($current_max>0)
$current_max--;
else
return -1;
}
}
// finally check for
// unbalanced string
if ($current_max != 0)
return -1;
return $max;
}
// Driver Code
$s = "( ((X)) (((Y))) )";
echo maxDepth($s);
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript program to find the
// maximum depth of nested parenthesis
// in a given expression
// Function takes a string and returns the
// maximum depth nested parenthesis
function maxDepth(S)
{
// Current count
let current_max = 0;
// Overall maximum count
let max = 0;
let n = S.length;
// Traverse the input string
for(let i = 0; i < n; i++)
{
if (S[i] == '(')
{
current_max++;
// Update max if required
if (current_max > max)
{
max = current_max;
}
}
else if (S[i] == ')')
{
if (current_max > 0)
{
current_max--;
} else
{
return -1;
}
}
}
// Finally check for unbalanced string
if (current_max != 0)
{
return -1;
}
return max;
}
// Driver code
let s = "( ((X)) (((Y))) )";
document.write(maxDepth(s));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n) where n is number of elements in given string. As, we are using a loop to traverse N times so it will cost us O(N) time.
Auxiliary Space: O(1), as we are not using any extra space.
Similar Reads
Number of balanced parentheses substrings Given a balanced parentheses string which consists of '(' and ')'. The task is to find the number of balanced parentheses substrings in the given string Examples : Input : str = "()()()" Output : 6 (), (), (), ()(), ()(), ()()()Input : str = "(())()" Output : 4 (), (()), (), (())() Approach : Let us
6 min read
Minimum number of Parentheses to be added to make it valid Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: s
9 min read
Count all indices of cyclic regular parenthesis Given a string S of length N, consisting of only opening '(' and closing ')' parenthesis. The task is to find all indices 'K' such that S[K...N-1] + S[0...K-1] is a regular parenthesis. A regular parentheses string is either empty (""), "(" + str1 + ")", or str1 + str2, where str1 and str2 are regul
7 min read
Print all combinations of balanced parentheses Given a number n, print all combinations of balanced parentheses of length n.Note: A sequence of parentheses is balanced if every opening bracket ( has a corresponding closing bracket ) in the correct order.Examples: Input: n = 2Output: ["( )"]Explanation: Only one valid sequence can be formed using
7 min read
Find if an expression has duplicate parenthesis or not Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis. Examples: Below expressions have duplicate parenthesis - ((a+b)+((c+d)))The subexpression "c+d" is surrounded by twopairs
6 min read