Find maximum depth of nested parenthesis in a string
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++
#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);
else if (s[i] == ')' ) {
if (count < st.size())
count = st.size();
st.pop();
}
}
return count;
}
int main()
{
string s = "( ((X)) (((Y))) )" ;
cout << maxDepth(s);
return 0;
}
|
Java
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);
else if (s.charAt(i) == ')' )
{
if (count < st.size())
count = st.size();
st.pop();
}
}
return count;
}
public static void main (String[] args) {
System.out.println(maxDepth( "( ((X)) (((Y))) )" ));
}
}
|
Python3
def maxDepth(s):
count = 0
st = []
for i in range ( len (s)):
if (s[i] = = '(' ):
st.append(i)
elif (s[i] = = ')' ):
if (count < len (st)):
count = len (st)
st.pop()
return count
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
|
C#
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);
} else {
if (s[i]== ')' ){
if (count<st.Count){
count=st.Count;
}
st.Pop();
}
}
}
return count;
}
static public void Main (){
Console.Write(maxDepth( "( ((X)) (((Y))) )" ));
}
}
|
Javascript
<script>
function maxDepth(s){
let count = 0
let st = []
for (let i=0;i<s.length;i++){
if (s[i] == '(' )
st.push(i)
else if (s[i] == ')' ){
if (count < st.length)
count = st.length
st.pop()
}
}
return count
}
let s = "( ((X)) (((Y))) )"
document.write(maxDepth(s), "</br>" )
</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++
#include <iostream>
using namespace std;
int maxDepth(string S)
{
int current_max = 0;
int max = 0;
int n = S.length();
for ( int i = 0; i < n; i++)
{
if (S[i] == '(' )
{
current_max++;
if (current_max > max)
max = current_max;
}
else if (S[i] == ')' )
{
if (current_max > 0)
current_max--;
else
return -1;
}
}
if (current_max != 0)
return -1;
return max;
}
int main()
{
string s = "( ((X)) (((Y))) )" ;
cout << maxDepth(s);
return 0;
}
|
Java
class GFG {
static int maxDepth(String S) {
int current_max = 0 ;
int max = 0 ;
int n = S.length();
for ( int i = 0 ; i < n; i++) {
if (S.charAt(i) == '(' ) {
current_max++;
if (current_max > max) {
max = current_max;
}
} else if (S.charAt(i) == ')' ) {
if (current_max > 0 ) {
current_max--;
} else {
return - 1 ;
}
}
}
if (current_max != 0 ) {
return - 1 ;
}
return max;
}
public static void main(String[] args) {
String s = "( ((X)) (((Y))) )" ;
System.out.println(maxDepth(s));
}
}
|
Python3
def maxDepth(S):
current_max = 0
max = 0
n = len (S)
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
if current_max ! = 0 :
return - 1
return max
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
|
C#
using System;
class GFG {
static int maxDepth( string S)
{
int current_max = 0;
int max = 0;
int n = S.Length;
for ( int i = 0; i < n; i++)
{
if (S[i] == '(' )
{
current_max++;
if (current_max > max)
{
max = current_max;
}
}
else if (S[i] == ')' )
{
if (current_max > 0)
{
current_max--;
}
else
{
return -1;
}
}
}
if (current_max != 0)
{
return -1;
}
return max;
}
public static void Main()
{
string s = "(((X)) (((Y))))" ;
Console.Write(maxDepth(s));
}
}
|
PHP
<?php
function maxDepth( $S )
{
$current_max = 0;
$max = 0;
$n = strlen ( $S );
for ( $i = 0; $i < $n ; $i ++)
{
if ( $S [ $i ] == '(' )
{
$current_max ++;
if ( $current_max > $max )
$max = $current_max ;
}
else if ( $S [ $i ] == ')' )
{
if ( $current_max >0)
$current_max --;
else
return -1;
}
}
if ( $current_max != 0)
return -1;
return $max ;
}
$s = "( ((X)) (((Y))) )" ;
echo maxDepth( $s );
?>
|
Javascript
<script>
function maxDepth(S)
{
let current_max = 0;
let max = 0;
let n = S.length;
for (let i = 0; i < n; i++)
{
if (S[i] == '(' )
{
current_max++;
if (current_max > max)
{
max = current_max;
}
}
else if (S[i] == ')' )
{
if (current_max > 0)
{
current_max--;
} else
{
return -1;
}
}
}
if (current_max != 0)
{
return -1;
}
return max;
}
let s = "( ((X)) (((Y))) )" ;
document.write(maxDepth(s));
</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.
Last Updated :
06 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...