# 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 : 10From 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++

 `// CPP Program to find length of longest balanced``// parentheses prefix.``#include ``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 Program``int` `main()``{``    ``char` `str[] = ``"((()())())(("``;``    ``int` `n = ``strlen``(str);` `    ``cout << maxbalancedprefix(str, n) << endl;``    ``return` `0;``}`

## Java

 `// 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

 `# 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 Code``str` `=` `'((()())())(('``n ``=` `len``(``str``)``print``(maxbalancedprefix (``str``, n))` `# This code is contributed by "Abhishek Sharma 44"`

## C#

 `// 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`

## Javascript

 ``

## PHP

 ``

Output
```10

```

Time complexity: O(length(str))
Auxiliary space: O(1)

Another Approach:

Initialize two variables, balance and max_len, to zero.

Traverse the string from left to right:

a. If the current character is ‘(‘, increment the balance variable, else decrement it.

b. If the balance variable is negative, reset it to zero and move the max_len pointer to the right.

c. If the balance variable is zero, update the max_len if the current substring length is greater than max_len.

Return max_len.

## C++

 `#include ``using` `namespace` `std;` `int` `main() {``    ``string str = ``"(()))())"``;``    ``int` `n = str.length();``    ` `    ``int` `balance = 0;``    ``int` `max_len = 0;``    ` `    ``// Traverse the string from left to right and find the length of the longest balanced parentheses prefix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(str[i] == ``'('``) {``            ``balance++;``        ``} ``else` `{``            ``balance--;``        ``}``        ``if` `(balance < 0) {``            ``balance = 0;``            ``max_len = i + 1;``        ``} ``else` `if` `(balance == 0) {``            ``max_len = i + 1 > max_len ? i + 1 : max_len;``        ``}``    ``}``    ` `    ``cout << ``"Length of longest balanced parentheses prefix is: "` `<< max_len <

## C

 `#include ``#include ` `int` `main() {``    ``char` `str[] = ``"(()))())"``;``    ``int` `n = ``strlen``(str);``    ` `    ``int` `balance = 0;``    ``int` `max_len = 0;``    ` `    ``// Traverse the string from left to right and find the length of the longest balanced parentheses prefix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(str[i] == ``'('``) {``            ``balance++;``        ``} ``else` `{``            ``balance--;``        ``}``        ``if` `(balance < 0) {``            ``balance = 0;``            ``max_len = i + 1;``        ``} ``else` `if` `(balance == 0) {``            ``max_len = i + 1 > max_len ? i + 1 : max_len;``        ``}``    ``}``    ` `    ``printf``(``"Length of longest balanced parentheses prefix is: %d\n"``, max_len);``    ` `    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {``    ``public` `static` `void` `main(String[] args) {``        ``String str = ``"(()))())"``;``        ``int` `n = str.length();``        ``int` `balance = ``0``;``        ``int` `max_len = ``0``;` `        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``if` `(str.charAt(i) == ``'('``) {``                ``balance++;``            ``} ``else` `{``                ``balance--;``            ``}``            ``if` `(balance < ``0``) {``                ``balance = ``0``;``                ``max_len = i + ``1``;``            ``} ``else` `if` `(balance == ``0``) {``                ``max_len = i + ``1` `> max_len ? i + ``1` `: max_len;``            ``}``        ``}``        ``System.out.println(``"Length of longest balanced parentheses prefix is: "` `+ max_len);``    ``}``}`

## Python3

 `# Nikunj Sonigara` `str` `=` `"(()))())"``n ``=` `len``(``str``)` `balance ``=` `0``max_len ``=` `0` `# Traverse the string from left to right and find the length of the longest balanced parentheses prefix``for` `i ``in` `range``(n):``    ``if` `str``[i] ``=``=` `'('``:``        ``balance ``+``=` `1``    ``else``:``        ``balance ``-``=` `1``    ``if` `balance < ``0``:``        ``balance ``=` `0``        ``max_len ``=` `i ``+` `1``    ``elif` `balance ``=``=` `0``:``        ``max_len ``=` `max``(i ``+` `1``, max_len)` `print``(``"Length of longest balanced parentheses prefix is:"``, max_len)`

## C#

 `using` `System;` `class` `Program``{``    ``static` `void` `Main(``string``[] args)``    ``{``        ``string` `str = ``"(()))())"``;``        ``int` `n = str.Length;``        ``int` `balance = 0;``        ``int` `max_len = 0;` `        ``for` `(``int` `i = 0; i < n; i++)``        ``{``            ``if` `(str[i] == ``'('``)``            ``{``                ``balance++;``            ``}``            ``else``            ``{``                ``balance--;``            ``}``            ``if` `(balance < 0)``            ``{``                ``balance = 0;``                ``max_len = i + 1;``            ``}``            ``else` `if` `(balance == 0)``            ``{``                ``max_len = i + 1 > max_len ? i + 1 : max_len;``            ``}``        ``}``        ``Console.WriteLine(``"Length of longest balanced parentheses prefix is: "` `+ max_len);``    ``}``}`

## Javascript

 `// Javascript code addition ` `let str = ``"(()))())"``;``let n = str.length;` `let balance = 0;``let max_len = 0;` `// Traverse the string from left to right and find the length of the longest balanced parentheses prefix``for` `(let i = 0; i < n; i++) {``    ``if` `(str[i] === ``'('``) {``        ``balance++;``    ``} ``else` `{``        ``balance--;``    ``}``    ``if` `(balance < 0) {``        ``balance = 0;``        ``max_len = i + 1;``    ``} ``else` `if` `(balance === 0) {``        ``max_len = i + 1 > max_len ? i + 1 : max_len;``    ``}``}` `console.log(``"Length of longest balanced parentheses prefix is: "` `+ max_len);` `// The code is contributed by Arushi Goel.`

Output
```Length of longest balanced parentheses prefix is: 8

```

time complexity of O(n), where n is the length of the string

space complexity of O(1)

Previous
Next