Check if concatenation of two strings is balanced or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have two bracket sequences s and t with only these characters '(' and ')'. We have to check whether the concatenated string of s and t is balanced or not. The concatenation can be done by s | t or t | s.

So, if the input is like s = "()()))", t = "()(()(", then the output will be True because if we concatenate t | s, then we will get "()(()(()()))", which is balanced.

To solve this, we will follow these steps −

  • Define a function is_balanced_parenthesis() . This will take string
  • stack := a new list
  • for i in range 0 to size of string, do
    • if string[i] is same as '(', then
      • push string[i] into stack
    • otherwise,
      • if stack is empty, then
        • return False
      • otherwise,
        • pop from stack
  • if stack is not empty, then
    • return False
  • return True
  • From the main method do the following −
  • if is_balanced_parenthesis(s + t) is true, then
    • return True
  • return is_balanced_parenthesis(t + s)

Let us see the following implementation to get better understanding −


 Live Demo

def is_balanced_parenthesis(string):
   stack = []
   for i in range(len(string)):
      if string[i] == '(':
         if len(stack) == 0:
            return False
   if len(stack) > 0:
      return False
   return True
def solve(s, t):
   if is_balanced_parenthesis(s + t):
      return True
   return is_balanced_parenthesis(t + s)
s = "()()))"
t = "()(()("
print(solve(s, t))


"()()))", "()(()("


Published on 30-Dec-2020 18:15:41