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

335 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements