Length of longest balanced parentheses prefix

09 Jun, 2022
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++
Java
Python3
C#
PHP
Javascript
// 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 first bracket is closing bracket        // then this condition would help        if (sum < 0)            break;         // If sum is 0, store the index        // value.        if (sum == 0)            maxi = i + 1;    }     return maxi;} // Driven Programint main(){    char str[] = "((()())())((";    int n = strlen(str);     cout << maxbalancedprefix(str, n) << endl;    return 0;}
// 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 first bracket is closing bracket            // then this condition would help            if (sum < 0)                break;             // If sum is 0, store the index            // value.            if (sum == 0)                maxi = i + 1;        }         return maxi;    }     // 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
# 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 first bracket is closing bracket       # then this condition would help        if _sum < 0:            break                     # If sum is 0, store the        # index value.        if _sum == 0:            maxi = i + 1    return maxi      # Driver Codestr = '((()())())(('n = len(str)print(maxbalancedprefix (str, n)) # This code is contributed by "Abhishek Sharma 44"
// 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 first bracket is closing bracket            // then this condition would help            if (sum < 0)                break;             // If sum is 0, store the index            // value.            if (sum == 0)                maxi = i + 1;        }         return maxi;    }     // Driven Program    public static void Main()    {        string str = "((()())())((";        int n = str.Length;         Console.WriteLine(maxbalancedprefix(str, n));    }} // This code is contributed by vt_m
<?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 < 0)            break;         // If sum is 0, store the index        // value.        if ($sum == 0)            $maxi = $i+1;    }     return $maxi;} // Driver Code$str = array('(', '(', '(', ')', '(', ')', ')', '(', ')', ')', '(', '(');$n = count($str); echo maxbalancedprefix($str, $n); // This code is contributed by anuj_67..?>
<script> // Javascript Program to find// length of longest balanced// parentheses prefix. // Return the length of longest// balanced parentheses// prefix.function maxbalancedprefix( str, n){    var sum = 0;    var maxi = 0;     // Traversing the string.    for (var 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 first bracket is closing bracket        // then this condition would help        if (sum < 0)            break;         // If sum is 0, store the index        // value.        if (sum == 0)            maxi = i + 1;    }     return maxi;} // Driven Programvar str = "((()())())((";var n = str.length;document.write( maxbalancedprefix(str, n)); </script>
10

Time complexity: O(length(str))Auxiliary space: O(1)  
Length of longest balanced parentheses prefix | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersLength of longest balanced parentheses prefix | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=yKoBPhyMRRc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
vt_m
sirjan13
smittal30
MayankAggarwal2
rrrtnx
hasani
Parentheses-Problems
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Longest Palindromic Substring | Set 1
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Check whether two strings are anagram of each other
Convert string to char array in C++
Reverse words in a given string
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string