- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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

- if count is same as 0 and size of temp > 0, then
- insert temp at the end of groups
- return groups

Let us see the following implementation to get better understanding −

## Example

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

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

- Related Questions & Answers
- Program to find maximum number of groups getting fresh donuts in Python
- Check for balanced parentheses in Python
- Program to find minimum number of monotonous string groups in Python
- Print all combinations of balanced parentheses in C++
- Program to check whether parentheses are balanced or not in Python
- Count pairs of parentheses sequences such that parentheses are balanced in C++
- Program to find maximum number of K-sized groups with distinct type items are possible in Python
- Program to find length of longest balanced subsequence in Python
- Program to find maximum number of eaten apples in Python
- Program to find number of friend groups in a set of friends connections in Python
- Program to find maximum number of non-overlapping substrings in Python
- Program to find number of columns flips to get maximum number of equal Rows in Python?
- Program to find maximum number of coins we can collect in Python
- Program to find maximum number of balls in a box using Python
- Program to find minimum number of deletions required from two ends to make list balanced in Python

Advertisements