Length of longest balanced parentheses prefix

Given a string of open bracket ‘(‘ and closed bracket ‘)’. The task is to find the length of longest balanced prefix.

Examples:

Input : S = "((()())())((" 
Output : 10
From index 0 to index 9, they are forming 
a balanced parentheses prefix.

Input : S = "()(())((()"
Output : 6



The idea is take value of open bracket ‘(‘ as 1 and value of close bracket ‘)’ as -1. Now start finding the prefix sum of the given string. The farthest index, say maxi, where the value of sum is 0 is the index upto which longest balanced prefix exists. So the answer would be maxi + 1.

Below is the implementation of this approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP Program to find length of longest balanced
// parentheses prefix.
#include <bits/stdc++.h>
using namespace std;
  
// Return the length of longest balanced parentheses 
// prefix.
int maxbalancedprefix(char str[], int n)
{
    int sum = 0;
    int maxi = 0;
  
    // Traversing the string.
    for (int i = 0; i < n; i++) {
  
        // If open bracket add 1 to sum.
        if (str[i] == '(')
            sum += 1;
  
        // If closed bracket subtract 1
        // from sum
        else
            sum -= 1;
  
        // If sum is 0, store the index
        // value.
        if (sum == 0)
            maxi = i;
    }
  
    return maxi + 1;
}
  
// Driven Program
int main()
{
    char str[] = "((()())())((";
    int n = strlen(str);
  
    cout << maxbalancedprefix(str, n) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find length of longest 
// balanced parentheses prefix.
import java.io.*;
  
class GFG {
      
    // Return the length of longest 
    // balanced parentheses prefix.
    static int maxbalancedprefix(String str, int n)
    {
        int sum = 0;
        int maxi = 0;
      
        // Traversing the string.
        for (int i = 0; i < n; i++) {
      
            // If open bracket add 1 to sum.
            if (str.charAt(i) == '(')
                sum += 1;
      
            // If closed bracket subtract 1
            // from sum
            else
                sum -= 1;
      
            // If sum is 0, store the index
            // value.
            if (sum == 0)
                maxi = i;
        }
      
        return maxi + 1;
    }
      
    // Driven Program
    public static void main (String[] args) 
    {
        String str = "((()())())((";
        int n = str.length();
      
        System.out.println( maxbalancedprefix(str, n));
              
    }
}
  
// This code is contributed by vt_m

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to find length of 
# longest balanced parentheses prefix.
  
# Function to return the length of 
# longest balanced parentheses prefix.
def maxbalancedprefix (str, n):
    _sum = 0
    maxi = 0
      
    # Traversing the string.
    for i in range(n):
      
        # If open bracket add 1 to sum.
        if str[i] == '(':
            _sum += 1
          
        # If closed bracket subtract 1
        # from sum
        else:
            _sum -= 1
              
        # If sum is 0, store the 
        # index value.
        if _sum == 0:
            maxi = i
    return maxi + 1
      
  
# Driver Code
str = '((()())())(('
n = len(str)
print(maxbalancedprefix (str, n))
  
#This code is contributed by "Abhishek Sharma 44"

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program to find length of longest 
// balanced parentheses prefix.
using System;
  
class GFG {
      
    // Return the length of longest 
    // balanced parentheses prefix.
    static int maxbalancedprefix(string str, int n)
    {
        int sum = 0;
        int maxi = 0;
      
        // Traversing the string.
        for (int i = 0; i < n; i++) {
      
            // If open bracket add 1 to sum.
            if (str[i] == '(')
                sum += 1;
      
            // If closed bracket subtract 1
            // from sum
            else
                sum -= 1;
      
            // If sum is 0, store the index
            // value.
            if (sum == 0)
                maxi = i;
        }
      
        return maxi + 1;
    }
      
    // Driven Program
    public static void Main () 
    {
        string str = "((()())())((";
        int n = str.Length;
      
        Console.WriteLine( maxbalancedprefix(str, n));
              
    }
}
  
// This code is contributed by vt_m

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP Program to find length 
// of longest balanced
// parentheses prefix.
  
// Return the length of longest
// balanced parentheses prefix.
function maxbalancedprefix($str, $n)
{
    $sum = 0;
    $maxi = 0;
  
    // Traversing the string.
    for ($i = 0; $i <$n; $i++) {
  
        // If open bracket add 1 to sum.
        if ($str[$i] == '(')
            $sum += 1;
  
        // If closed bracket subtract 1
        // from sum
        else
            $sum -= 1;
  
        // If sum is 0, store the index
        // value.
        if ($sum == 0)
            $maxi = $i;
    }
  
    return $maxi + 1;
}
  
// Driver Code
$str = array('(','(','(',')','(',')',')','(',')',')','(','(');
$n = count($str);
  
echo maxbalancedprefix($str, $n);
  
// This code is contributed by anuj_67..
?>

chevron_right



Output:

10


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vt_m, sirjan13



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.