# Split Parenthesis Sequence into maximum valid Substrings

• Difficulty Level : Medium
• Last Updated : 09 Jan, 2023

Given a String S which contains balanced Parentheses Brackets ( i.e ‘(‘ and ‘)’ ), we need to split them in such a way that they form the maximum number of balanced groups.

Examples:

Input:  S = “()()(()())()”
Output:  (), (), (()()), ()

Input:  S = “()()”
Output:  (), ()

Input:  S = “()()(())”
Output:  (), (), (())

Approach: To solve the problem follow the below idea:

We need to declare two variables, one to keep the count of Opening Braces (say count_o) and the other to keep the count of the Closing Braces (i.e count _c). Then, we need to check when count_o and tcount _c is  equal and then we need to push the current substring as a part of the result.

Follow the steps to solve the problem:

• Declare a vector (say res) to store the answer.
• Declare two counters count_o for opening braces and count_c for closing braces.
• Maintain a current substring by  curr_str.
• Iterate through the string:
• Increment either count_o or count_c according to the combination of braces in the string.
• When count_o becomes equal to count_c, store the curr_str in res and redefine curr_str = “”.
• At last, return res as the result.

Below is the implementation of the above approach.

## C++

 `// C++ code to implement the approach` `#include ``using` `namespace` `std;` `// Function to find the valid substrings``vector Balanced_Groups(string s)``{``    ``vector res;` `    ``// To keep the count of opening braces.``    ``int` `count_o = 0;` `    ``// To keep the count of closing braces.``    ``int` `count_c = 0;` `    ``// To maintain the current string.``    ``string curr_str = ``""``;` `    ``int` `n = s.size();` `    ``// If the size of the string is zero.``    ``if` `(n == 0)``        ``return` `res;` `    ``// Loop to find the valid substrings``    ``for` `(``int` `i = 0; i < n; i++) {``        ``curr_str += s[i];` `        ``// Incrementing the count of``        ``// opening braces.``        ``if` `(s[i] == ``'('``) {``            ``count_o++;``        ``}` `        ``// Incrementing the count of``        ``// closing braces.``        ``if` `(s[i] == ``')'``) {``            ``count_c++;``        ``}` `        ``// To check for a balanced group``        ``// and push it to vector res.``        ``if` `(count_o == count_c) {``            ``res.push_back(curr_str);``            ``curr_str = ``""``;``        ``}``    ``}` `    ``// Returning the vector res.``    ``return` `res;``}` `// Driver Code``int` `main()``{``    ``string s = ``"()()(()())()"``;``    ``vector v;` `    ``// Function call``    ``v = Balanced_Groups(s);` `    ``for` `(``auto` `i : v)``        ``cout << i << ``" "``;` `    ``return` `0;``}`

## Java

 `// Java code to implement the approach``import` `java.util.*;` `public` `class` `Main``{``  ` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``String s = ``"()()(()())()"``;``    ``List v = ``new` `ArrayList<>();` `    ``// Function call``    ``v = Balanced_Groups(s);` `    ``for` `(String i : v) {``      ``System.out.print(i + ``" "``);``    ``}``  ``}` `  ``// Function to find the valid substrings``  ``public` `static` `List Balanced_Groups(String s)``  ``{``    ``List res = ``new` `ArrayList<>();` `    ``// To keep the count of opening braces.``    ``int` `count_o = ``0``;` `    ``// To keep the count of closing braces.``    ``int` `count_c = ``0``;` `    ``// To maintain the current string.``    ``String curr_str = ``""``;` `    ``int` `n = s.length();` `    ``// If the size of the string is zero.``    ``if` `(n == ``0``)``      ``return` `res;` `    ``// Loop to find the valid substrings``    ``for` `(``int` `i = ``0``; i < n; i++) {``      ``curr_str += s.charAt(i);` `      ``// Incrementing the count of``      ``// opening braces.``      ``if` `(s.charAt(i) == ``'('``) {``        ``count_o++;``      ``}` `      ``// Incrementing the count of``      ``// closing braces.``      ``if` `(s.charAt(i) == ``')'``) {``        ``count_c++;``      ``}` `      ``// To check for a balanced group``      ``// and push it to vector res.``      ``if` `(count_o == count_c) {``        ``res.add(curr_str);``        ``curr_str = ``""``;``      ``}``    ``}``    ``// Returning the vector res.``    ``return` `res;``  ``}``}` `// This code is contributed by Tapesh(tapeshdua420)`

## Python3

 `# Python code to implement the approach` `# Function to find the valid substrings``def` `Balanced_Groups(s):``    ``res ``=` `[]` `    ``# To keep the count of opening braces.``    ``count_o ``=` `0` `    ``# To keep the count of closing braces.``    ``count_c ``=` `0` `    ``# To maintain the current string.``    ``curr_str ``=` `""` `    ``n ``=` `len``(s)` `    ``# If the size of the string is zero.``    ``if` `n ``=``=` `0``:``        ``return` `res` `    ``# Loop to find the valid substrings``    ``for` `i ``in` `range``(n):``        ``curr_str ``+``=` `s[i]` `        ``# Incrementing the count of``        ``# opening braces.``        ``if` `s[i] ``=``=` `'('``:``            ``count_o ``+``=` `1` `        ``# Incrementing the count of``        ``# closing braces.``        ``if` `s[i] ``=``=` `')'``:``            ``count_c ``+``=` `1` `        ``# To check for a balanced group``        ``# and push it to vector res.``        ``if` `count_o ``=``=` `count_c:``            ``res.append(curr_str)``            ``curr_str ``=` `""` `    ``# Returning the vector res.``    ``return` `res`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``s ``=` `"()()(()())()"``    ``v ``=` `[]` `    ``# Function call``    ``v ``=` `Balanced_Groups(s)``    ``print``(v)` `# This code is contributed by Tapesh(tapeshdua420)`

## C#

 `// C# code to implement the approach``using` `System;``using` `System.Collections.Generic;` `class` `Program``{` `  ``// Driver Code``  ``static` `void` `Main(``string``[] args)``  ``{``    ``string` `s = ``"()()(()())()"``;``    ``List<``string``> v = ``new` `List<``string``>();` `    ``// Function call``    ``v = Balanced_Groups(s);` `    ``foreach``(``string` `i ``in` `v) { Console.Write(i + ``" "``); }``  ``}` `  ``// Function to find the valid substrings``  ``public` `static` `List<``string``> Balanced_Groups(``string` `s)``  ``{``    ``List<``string``> res = ``new` `List<``string``>();` `    ``// To keep the count of opening braces.``    ``int` `count_o = 0;` `    ``// To keep the count of closing braces.``    ``int` `count_c = 0;` `    ``// To maintain the current string.``    ``string` `curr_str = ``""``;` `    ``int` `n = s.Length;` `    ``// If the size of the string is zero.``    ``if` `(n == 0)``      ``return` `res;` `    ``// Loop to find the valid substrings``    ``for` `(``int` `i = 0; i < n; i++) {``      ``curr_str += s[i];` `      ``// Incrementing the count of``      ``// opening braces.``      ``if` `(s[i] == ``'('``) {``        ``count_o++;``      ``}` `      ``// Incrementing the count of``      ``// closing braces.``      ``if` `(s[i] == ``')'``) {``        ``count_c++;``      ``}` `      ``// To check for a balanced group``      ``// and push it to vector res.``      ``if` `(count_o == count_c) {``        ``res.Add(curr_str);``        ``curr_str = ``""``;``      ``}``    ``}` `    ``// Returning the vector res.``    ``return` `res;``  ``}``}` `// This code is contributed by Tapesh(tapeshdua420)`

## Javascript

 `   ``// JavaScript code for the above approach` `   ``// Function to find the valid substrings``   ``function` `Balanced_Groups(s) {``     ``let res = [];` `     ``// To keep the count of opening braces.``     ``let count_o = 0;` `     ``// To keep the count of closing braces.``     ``let count_c = 0;` `     ``// To maintain the current string.``     ``let curr_str = ``""``;` `     ``let n = s.length;` `     ``// If the size of the string is zero.``     ``if` `(n == 0)``       ``return` `res;` `     ``// Loop to find the valid substrings``     ``for` `(let i = 0; i < n; i++) {``       ``curr_str += s[i];` `       ``// Incrementing the count of``       ``// opening braces.``       ``if` `(s[i] == ``'('``) {``         ``count_o++;``       ``}` `       ``// Incrementing the count of``       ``// closing braces.``       ``if` `(s[i] == ``')'``) {``         ``count_c++;``       ``}` `       ``// To check for a balanced group``       ``// and push it to vector res.``       ``if` `(count_o == count_c) {``         ``res.push(curr_str);``         ``curr_str = ``""``;``       ``}``     ``}` `     ``// Returning the vector res.``     ``return` `res;``   ``}` `   ``// Driver Code``   ``let s = ``"()()(()())()"``;``   ``let v;` `   ``// Function call``   ``v = Balanced_Groups(s);` `   ``for` `(let i of v)``     ``process.stdout.write(i + ``" "``);` `// This code is contributed by Potta Lokesh`

Output

`() () (()()) () `

Time Complexity: O(N), as only one for loop is used.
Auxiliary Space: O(N), an extra storage is used to store the valid substrings.

My Personal Notes arrow_drop_up