# Program to find maximum number of balanced groups of parentheses in Python

Suppose we have a string s that contains balanced parentheses "(" and ")", we have to split them into the maximum number of balanced groups.

So, if the input is like "(()())()(())", then the output will be ['(()())', '()', '(())']

To solve this, we will follow these steps −

• temp := blank string
• groups := a new list
• count := 0
• for each character b in s, do
• if count is same as 0 and size of temp > 0, then
• insert temp at the end of groups
• temp := blank string
• temp := temp concatenate b
• if b is same as '(', then
• count := count + 1
• otherwise,
• count := count - 1
• insert temp at the end of groups
• return groups

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, s):
temp = ''
groups = []
count = 0
for b in s:
if count == 0 and len(temp) > 0:
groups.append(temp)
temp = ''
temp += b
if b == '(':
count += 1
else:
count -= 1
groups.append(temp)
return groups
s = "(()())()(())"
ob = Solution()
print(ob.solve(s))

## Input

"(()())()(())"

## Output

['(()())', '()', '(())']

Updated on: 06-Oct-2020

291 Views
{"ft_lang_label":"__label__en","ft_lang_prob":0.72920173,"math_prob":0.99411976,"size":1774,"snap":"2023-40-2023-50","text_gpt3_token_len":483,"char_repetition_ratio":0.10960452,"word_repetition_ratio":0.12352941,"special_character_ratio":0.33032694,"punctuation_ratio":0.100323625,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9991135,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-09-22T14:20:14Z\",\"WARC-Record-ID\":\"<urn:uuid:253da285-d2ff-4b69-a517-20af883d04e7>\",\"Content-Length\":\"71976\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ec898163-de9f-4fc8-a727-7bd71535aa47>\",\"WARC-Concurrent-To\":\"<urn:uuid:d32b0678-d999-475d-a2d4-c900b118d452>\",\"WARC-IP-Address\":\"192.229.210.176\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/program-to-find-maximum-number-of-balanced-groups-of-parentheses-in-python\",\"WARC-Payload-Digest\":\"sha1:YWU3HD3DRGL2X6CIAT5RJ4AD3KP7QGNB\",\"WARC-Block-Digest\":\"sha1:66RUS7YBVMSFRCOEN4WBJZ4MQITWRGRA\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-40/CC-MAIN-2023-40_segments_1695233506420.84_warc_CC-MAIN-20230922134342-20230922164342-00047.warc.gz\"}"}